Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

javascript - UseContext React hooks

how can I use UseContext to make this const '' data '' accessible throughout my project? I'm trying to implement but I can't. It doesn't have to be with UseContext, it was just a way that I researched

import api from '../../services/api';
import React, {useContext} from 'react';


export default async function getItems() {
  try {
    const data = await api.get("/list-results");
    return data;
    
  } catch (error) {
    return error
  }
}
question from:https://stackoverflow.com/questions/65643346/usecontext-react-hooks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, create yourself a context:

const MyContext = React.createContext(defaultValue);

Then call your getItems() and store the result in a state and pass it to your context provider:

const [storedData, setStoredData] = useState<MyData | null>(null);
useEffect(() => {
    getItems().then((data) => setStoredData(data));
}, []);
if (!storedData) return <div>Loading</div>;
return <MyContext.Provider value={}><MyApp/> </MyContext.Provider>;

Ideally do some more error handling in there.

And finally, get your context using useContext in a component somewhere in MyApp:

const data = useContext(MyContext);

Code is untested and should be seen as pseudo-code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...