Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Context : Get Data from API and call API whenever some events happens in React Component

I am new to React Context. I need to call the API in react context to use its data throughout my react application. Also the same API needs to be called on some CRUD operation on various component of react application.

For now I am storing API data in redux which I don't want to store.

Here is what I have tried..

context.js File

import React, { useState, createContext,useEffect } from 'react';
import {getData} from './actionMethods';

const NewContext = createContext();

function newContextProvider(props) {
    useEffect(async () => {
         const {dataValue}  = await getData()

         console.log("Data " , dataValue)    
     }, [])
     
     return (
        <NewContext.Provider
            value={{
                state: {
                    
                },
                actions: {
                    
                }
            }}
        >
            {props.children}
        </NewContext.Provider>
    );
}


const newContextConsumer = newContext.Consumer;

export { newContextProvider, newContextConsumer, newGridContext };

actionMethods.js

export function getData() {
    let config = getInstance('GET', `${prefix}/xyz/list`)
    return axios(config).then(res => res.data).catch(err => {
      console.log(err)
    })
  }

when any CRUD operation performs , I need to call the API from the context.js file to get the data from API and store in the context.

Any help would be great.

Thank You.

like image 924
Xperia Reno Avatar asked Oct 16 '22 08:10

Xperia Reno


People also ask

How can I avoid component re use problem with context API?

If you need to have some data accessible by many components at different nesting levels, then you should use the Context API. React docs advises that we 'apply it sparingly because it makes component reuse more difficult. ' In other words, you might not be able to reuse your components 'out of context'.


1 Answers

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.

like image 52
Alvaro Avatar answered Oct 23 '22 02:10

Alvaro