Answer the question
In order to leave comments, you need to log in
How to initialize state on first load of React component?
Hello!
Recently started learning React. I am working on a small project and I have this problem.
There is this code:
const Control = () => {
const [actionRow, setActionRow] = useState();
const { data,
getData } = useContext(DBContext);
useEffect(() => {
getData();
}, []);
const changeActionRow = (tr) => {
setActionRow(tr);
};
return (
<>
<HeaderData />
{
data.control &&
<Table>
<TableHeader title={tableTitle} />
<TableBodyControl
data={data}
actionRow={actionRow}
setActionRow={changeActionRow}
/>
</Table>
}
}
export const DBState = ({children}) => {
const initialState = {
data: {}
}
const [state, dispatch] = useReducer(DBReducer, initialState);
const getData = async () => {
const data = await request('/api/data');
dispatch({type: DATA, data});
}
return (
<DBContext.Provider value={{
data: state,
getData, setData
}}>
{ children }
</DBContext.Provider>
)
}
export const DBReducer = (state, action) => {
switch (action.type) {
case DATA:
return ({
...action.data
});
default: return state
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question