V
V
veteral2020-10-29 15:05:39
React
veteral, 2020-10-29 15:05:39

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
    }
}

How to initialize the actionRow on the first load of the Control component, i.e. get the first element of an array of data objects?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question