AlexisTercero55 / contact-list

https://alexistercero55.github.io/contact-list/
1 stars 0 forks source link

Actions to change profile State #9

Open AlexisTercero55 opened 1 year ago

AlexisTercero55 commented 1 year ago

Use flux-standard-action to implement state changes on profile data

AlexisTercero55 commented 1 year ago

Create an initial state

Three profiles were created with ProfileData() factory. https://github.com/AlexisTercero55/contact-list/blob/b0fa5758514460431d4109f6563aa7eb5ce69658/src/context/ProfileContext.jsx#L26

AlexisTercero55 commented 1 year ago

Define actions to update the State

https://github.com/AlexisTercero55/contact-list/blob/fa4f0b59937a6952eff23cc301138e8bcf4913e6/src/context/ProfileContext.jsx#L23

export const ProfileActions = {
  changeProject : 'Profile/Project',
  deleteProfile : 'Profile/Delete'//!FIXME: needs a user confirm to delete profile
}
AlexisTercero55 commented 1 year ago

Create a reducer to perfom state changes according actions definition

https://github.com/AlexisTercero55/contact-list/blob/fa4f0b59937a6952eff23cc301138e8bcf4913e6/src/context/ProfileContext.jsx#L37

export const ProfileReducer = (state=[ProfileData()],action)=>{
  //const { type, payload } = action;
  let newState;
  switch(action.type)
  {
    case ProfileActions.deleteProfile:
      console.log('To delete profile: ', action.index);
      newState = [...state]; // make a copy of the state array
      newState.splice(action.index, 1); // remove the object at the specified index
      return newState;

    default:
      return state;
  }
}
AlexisTercero55 commented 1 year ago

Create a context and link whith its reducer and InitialState inside a context provider component

https://github.com/AlexisTercero55/contact-list/blob/fa4f0b59937a6952eff23cc301138e8bcf4913e6/src/context/ProfileContext.jsx#L61 https://github.com/AlexisTercero55/contact-list/blob/fa4f0b59937a6952eff23cc301138e8bcf4913e6/src/context/ProfileContext.jsx#L62

export const ProfileContext = createContext(ProfileData());
export const ProfileContextProvider = ({children})=>{

  const [state, dispatch] = useReducer(ProfileReducer, InitialState)

  return (
    <ProfileContext.Provider value={[state, dispatch]}>
      {children}
    </ProfileContext.Provider>
  )
}