score:3
Accepted answer
first we create the context and pass it an initial value.
in order to fetch data and keep track of the returned value, we create a state inside the component. this component will manage the fetched data and pass it in the context provider.
to call an async function inside useeffect
we need to wrap it and call it inside useeffect
callback.
export const newcontext = createcontext({
my_data: {} // initial value
});
export const newcontextprovider = props => {
const [my_data, setmydata] = usestate({});
useeffect(() => {
const fetchmydata = async () => {
const { datavalue } = await getdata();
if (datavalue) {
setmydata(datavalue);
} else {
// there was an error fetching the data
}
};
fetchmydata();
}, []);
return (
<newcontext.provider
value={{
my_data
}}
>
{props.children}
</newcontext.provider>
);
};
to use this context in a component we use the usecontext
hook. remember that this component needs to be wrapped by the provider we just created.
import react, { usecontext } from "react";
import { newcontext } from "./newcontext"; // the file where the context was created
export const mycomponent = props => {
const { my_data } = usecontext(newcontext);
return //...
};
let me know if something is not clear.
Source: stackoverflow.com
Related Query
- React Context : Get Data from API and call API whenever some events happens in React Component
- Set the data in React Context from asynchronous API call
- get data from multiple react child and send into one API
- React and Express: Using Axios to GET data from 3rd party API
- React JS: Get Context Data After getting success on API Call
- Best practice to handle data from API call and render React components
- Best way to fetch data from a REST api using react hooks and context for state management?
- How to get data from Api first and then call the my function?
- I do not know how to store json data from an api call within a nodejs express server, and send it to a react native client
- I made an API call fetching data from it on a React component and passed it on to a state. I want to use the same data on another component too
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- how to get spesific data from api with axios and react js?
- Displaying and mapping data from axios API call into React
- How can i get a single data from local api using react and redux?
- Call and store data from a API in React Reducer
- React - get data from API and show in return using MAP function
- Rest API get call - put data in array - with typescript and react
- How to concatenate URL and string, and get data from API at click a button using axios in REACT JS
- Call function in react to get API data from componentDidMount
- Get object data and target element from onClick event in react js
- How to get the data from React Context Consumer outside the render
- React Select - How to show / iterate through data from api call in option instead of hardcoding options?
- React and Flux: "dispatch in the middle of a dispatch" to show error message from an API call
- ReactJS: get data from api and map data
- How to get data from react context
- Fetching data from store if exists or call API otherwise in React
- How to Read image data from API and render in React Component
- Conditionally check value from context and then navigate after login in the same function call in React
- React is not updating the UI after receiveing data from the API call (using hooks)
- How to fetch and display data from Express API to a React app?
More Query from same tag
- Firebase: referencing docs with a string vs. referencing docs with a ref. Is there a difference?
- how to not add a user if it exists in a form react.js
- How can i use config variables in jsx file without importing in jsx?
- Is it bad to use Refs to change styles in react?
- Send React Form Input to Flask
- Value of datetime-local with React
- Turning on JSDoc in VS Code produces "Cannot use JSX unless the '--jsx' flag is provided"
- React js and Laravel Localization strings?
- React render insert adjacent element
- React this.state is undefined in component function
- Import React Material UI Icons dynamically
- Can I make string clickable in React?
- How do I loop an non-reactive array in Vue template without putting it in data property or computed property?
- React js Material ui Typography
- React router v5 with history - no content shown on routing
- Firebase: Invisible reCaptcha does not work in React JS
- React Hooks Not Allowing Me to Display Single Objects After Fetch Call
- Highcharts: Custom area outline for line joining each marker
- Problem with metronic react theme to typescript
- Using a variable that has been defined inside render, to use it inside return
- React: In react class component, should I use !== to match nextState with currentState
- Gatsby: Unable to Import Component with Graph Query
- Troubles animating react-router with framer-motion
- reactjs updating parent state from child in map function
- redux toolkit state resets
- Simple testing example of canvas element using Jest
- OnDoubleClick in react
- Enzyme mock function before componentWillMount
- Trying to check the item already printed and print items other than that
- Unhandled JS Exception: undefined is not an object (evaluating 'a.coords.latitude')', reason: 'Unhandled JS Exception: undefined is not an object