-1

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
  }
}

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.