Issue
STORY I have 3 Screens in a drawer navigator(with each screen having a headerRight "settings icon" which navigates to a screen with options to select. This uses a stack navigator.)
The screens in the drawer navigator has an input field, with a submit button. On submit, a new component renders with the values in the input field recalculated based off the values selected in "settings".
BUG any option selected in settings (whilst visually responsive and console logs correctly) on navigating away, back to the main screen, the value doesn't reflect. Also, on navigating back to the screen itself, options are reset to default values.
Heres the code:
DataContext.js
import React, {useEffect, useState} from "react";
// import AsyncStorage from '@react-native-community/async-storage';
export const DataContext = React.createContext();
dataSet = {
first: 0,
second: false,
third: "Under 65",
fourth: "",
};
export const DataProvider = ({ children }) => {
const [initialData, setInitialData] = useState(dataSet)
const updateData = (newData, name)=> {
setInitialData ((prevData) => ({
...prevData,
[name]: newData
}))
}
return (
<DataContext.Provider value={{ initialData, updateData,}}>
{children}
</DataContext.Provider>
);
};
Settings Screen
import { DataProvider, DataContext } from "../context/DataContext";
const Setting = () => {
return (
<View>
<Options name="test" />
</View>
)
}
export default () => {
return (
<DataProvider>
<Setting />
</DataProvider>
);
};
Options Component (within settings)
import { DataContext } from "../context/DataContext";
const Options = ({ navigation }) => {
const { initialData, updateData } = useContext(DataContext)
const [data, setData] = useState(initialData)
return (
<View style={{ width: "15%", }}>
<SwitchButton
value={data.niSelected}
callback={() => {
const updatedData = { ...data, niSelected: !data.niSelected };
setData(updatedData);
updateData(!data.third, "Over 65");
}}
/>
</View>
</View>
</View>
);
};
I tried below which works but obviously cant mutate state directly in react, which leads me to thing my updateData function in DataContext is the issue here.
initialData[name]: newData
Any suggestions on how to resolve this please?
Solution
Wrapping each screen in the Drawer as the provider as I did previously resulted in the bug described above.
Resolved this by wrapping the entire App, i.e. Stack Navigator(which has the drawer navigator in it) as the sole DataProvider.
Answered By - abic17
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.