I have set a three part Component for a filter menu. Component A) is the createContext which has an object with my globalData data and a function setData to change the data. When setData is triggered it retrieves data from the DB and updates the my globalData.data. Component B) Triggers component A and passes the appropriate values (This part works). Component C) is the useContext where it retrieves the data and users .Provider to display the data.
The problem is that Component C does not re-render any component.
Component A) Creates context and function to change context
import React, { createContext } from 'react';
import APIEndpoint from 'src/js/api/apAPIEndpoint.js';
const globalData={data:{kpi:[]}, filters:{date:'', login:'9166', country:[], city:[]}, setData:(field, value)=>{
globalData.filters = {...globalData.filters,[field]:value};
let fetchURL = `/APIURL?alias=${parseInt(globalData.filters.login)}&${globalData.filters.country.map((item)=>('country='+item.country)).join('&')}&${globalData.filters.city.map((item)=>('city='+item.city)).join('&')}`;
if(globalData.filters.login && globalData.filters.country.length>0 && globalData.filters.city.length>0){
APIEndpoint
.get(fetchURL)
.then(res => {
globalData.data={...globalData, data:res.data.data};
});
}
}
};
const GlobalDataContext = createContext(globalData);
export default GlobalDataContext;
Component B) Triggers context change in (A)
import React, {useContext} from 'react';
import GlobalDataContext from '/GlobalDataContext';
const globalData = useContext( GlobalDataContext );
const setGlobalData = globalData ? globalData.setData : null;
...
return(
<div>
<StyledSelect
onChange={(value) =>{
setGlobalData(props.valueField, value);
}} />
</div>
)
Component C) This is where it does not re-render. only want to re render one component under Section 2
import React, { useContext } from 'react';
import GlobalDataContext from '/GlobalDataContext';
const {data, setData} = useContext( GlobalDataContext );
...
return (
<>
<Helmet>
<title>Something - Home</title>
</Helmet>
<StencilResponsiveDesign sizes={[VIEWPORT_SIZES.S, VIEWPORT_SIZES.M]}>
...
{/* Section 1 */}
<FilterBar />
<Spacer height={50} />
{/* Section 2 */}
<GlobalDataContext.Provider value={globalData.data.kpi}>
<div>
<KpiWidget />
</div>
</GlobalDataContext.Provider>