5

In this project I'm using React.createContext() methode to manage the state. I can access to the state data by importing the Context.Consumer and using this consumer in the return methode of the class component(or functional component). See thie exemple bellow :

function App(){

  return(
    <Consumer>
      {value=>{
                const {basket} = value;
                return <p> { basket.length() } </p>
            }
      }
    </Consumer>
  )
}

The problem is i want to dispatch an action from the useEffect hook and not from the component return

this what i want to do :

function App() {

    useEffect(() => {
        auth.onAuthStateChanged(authUser => {
                if(authUser){
                    dispatch({ //I need to use dispatch methode here!!
                        type : 'SET_USER',
                        payload : authUser
                    })
                }
                else{
                    dispatch({ //I need to use dispatch methode here!!
                        type : 'SET_USER',
                        payload : null
                    })
                }
            })      

    }, [])
  
  return(...)
  
  }

StateProvider.js :

import React, { Component } from 'react';
const  Context = React.createContext();

// 1. Selector
export const getSubtotal = (basket)=> basket?.reduce((amount,item)=> item.price + amount ,0);

// 2. Reducer
const reducer = (state,action)=>{
    switch(action.type){
        case 'ADD_TO_BASKET' :
            return{
                basket : [action.payload, ...state.basket],
            };
        case 'DELETE_FROM_BASKET' :
            const index = state.basket.findIndex(item=>item.id === action.payload)
            let basketCopie = [...state.basket]
            basketCopie.splice(index,1)
            return{
                basket : basketCopie
            };
        case 'SET_USER' :
            return{
                user : action.payload
            };
        default :
            return state
    }
}

// 3. Provider Classe
export class Provider extends Component {
    state = {
        basket : [], 
        user : null,
        dispatch : action=> this.setState(state=> reducer(state,action))
    }
    render() {
        return (
            <Context.Provider value={this.state} > {/* the value change after any reducer call*/}
                {this.props.children}
            </Context.Provider>
        );
    }
}

// 4. Consumer
export const Consumer = Context.Consumer;
bilalo
  • 129
  • 1
  • 1
  • 7
  • why not to use redux if you use disputers. and another thing you don't need to export consumer you can export the context itself and then use the useContext hook to get the value you want – TalOrlanczyk Nov 29 '20 at 14:16

1 Answers1

-1

ok I know it's not quite an answer but I found a page that I think will help you a lot

context api with hooks

its go with you step by step and it;s help me alot

TalOrlanczyk
  • 1,205
  • 7
  • 21