unable to pas data (which is array) in initialisation of useReducer hook which contain array of object , Getting result in child component empty array in products initialisation.
I want same data in child component as same I passed.
code :
import React, { createContext, useContext, useEffect, useReducer, useState } from 'react'
import faker from "faker";
import { cartReducer } from './Reducer';
export const Cart = createContext();
const Context = ({ children }) => {
const [data, setProduct] = useState();
useEffect(() => {
var axios = require('axios');
var config = {
method: 'get',
url: '<apicalling here>',
headers: {
'Authorization': 'Token xyz'
}
};
axios(config)
.then(function (response) {
setProduct(response.data.cart[0].items);
})
.catch(function (error) {
console.log(error);
});
}, []);
console.warn("hello", data); //yes working, data rendering here
const [state, dispatch] = useReducer(cartReducer, {
products: data,
cart: [],
});
return <Cart.Provider value={{ state, dispatch }}>{children} </Cart.Provider>;
};
export default Context;
This is happening because the state of your reducer sets before the API call resolves.
And you are getting those updated data in console.log because you are updating it into the
datastate, but the reducer has access to the same previous data (reason: state of your reducer sets before API call resolves).
So, the solution to your problem is to create one action that dispatches your updated value of Products once you got the response from the API.
import React, { createContext, useContext, useEffect, useReducer, useState } from 'react' import faker from "faker"; import { cartReducer } from './Reducer';
const cartReducer = (state, { type, payload = {} }) => {
switch (type) {
case 'setProducts': {
return {...state, products: payload};
}
/*
Other actions
*/
default: {
// your default action
}
}
}
export const Cart = createContext();
const Context = ({ children }) => {
const [data, setProduct] = useState();
useEffect(() => {
var axios = require('axios');
var config = {
method: 'get',
url: '<apicalling here>',
headers: {
'Authorization': 'Token xyz'
}
};
axios(config)
.then(function (response) {
setProduct(response.data.cart[0].items);
dispatch({type: 'setProducts', payload: response.data.cart[0].items}) // <--- dispatch once you get data
})
.catch(function (error) {
console.log(error);
});
}, []);
console.warn("hello", data); //yes working, data rendering here
const [state, dispatch] = useReducer(cartReducer, {
products: [],
cart: [],
});
const value = {
products: state.products; // <-- access it from state
cart: state.cart
}
return <Cart.Provider value={value}>{children} </Cart.Provider>; // <--- change value here
};
export default Context;