score:0

you need to use 2 useeffect hooks, one for fetch data and second to proceed it:

useeffect(() => {
    getnotes();
}, []);

useeffect(() => {
  if (notes && notes.length) {
    ....setstate or what else
  }
}, [notes]);

score:0

my note state looks like:

import react, { usereducer } from 'react';
import clientaxios from '../../config/clientaxios';
import notecontext from './notecontext';
import notereducer  from './notereducer';
import {
  get_notes,
  add_note,
  delete_note,
  update_note,
} from '../../types';
const notestate = ({ children }) => {
  const initialstate = {
    notes: [],
    noteerror: false,
  };

  const [state, dispatch] = usereducer(notereducer, initialstate);

  const getnotes = async () => {
    try {
      const response = await clientaxios.get('/user/notes');
      dispatch({
        type: get_notes,
        payload: response.data
      })
    } catch (error) {
      console.log(error.response);
    }
  }

  const addnote = async data => {
    try {
      const response = await clientaxios.post('/addnote', data);
      dispatch({
        type: add_note,
        payload: response.data.data
      })
    } catch (error) {
      console.log(error.response);
    }
  }

  const updatenote = async (id, { title, description }) => {
    try {
      const response = await clientaxios.put(`updatenote/${id}`, { title, description });
      console.log(response.data);
      dispatch({
        type: update_note,
        payload: response.data
      })
    } catch (error) {
      console.log(error.response)
    }
  }

  const deletenote = async id => {
    try {
      await clientaxios.put(`/deletenote/${id}`);
      dispatch({
        type: delete_note,
        payload: id
      })
    } catch (error) {
      console.log(error.response);
    }
  }

  return(
    <notecontext.provider
      value={{
        notes: state.notes,
        noteerror: state.noteerror,
        getnotes,
        addnote,
        updatenote,
        deletenote,
      }}
    >
      {children}
    </notecontext.provider>
  );
}
 
export default notestate;

and my reducer:

import {
  get_notes,
  add_note,
  delete_note,
  update_note,
} from '../../types';
export default (action, state) => {
  switch(action.type) {
    case get_notes:
      return {
        ...state,
        notes: action.payload
      }
    case add_note:
      return {
        ...state,
        notes: [...state.notes, action.payload]
      }
    case update_note:
      return {
        ...state,
        notes: state.notes.map(note => note._id === action.payload._id ? action.payload : note)
      }
    case delete_note:
      return {
        ...state,
        notes: state.notes.filter(note => note._id !== action.payload),
      }
    default:
      return state;
  }
}

Related Query

More Query from same tag