riki
riki

Reputation: 1725

Redux create reducer expected

Good morning, while using redux I have the following error, I have configured the reducer and the actions what, what should I fix?

Error: Expected the reducer to be a function.

Code:

import {createStore} from "redux";

const initalUser={
    IdUtente: 0
 };

const store=createStore(
    initalUser
  )

function userset(state=initalUser,action,value){
    switch(action){
        case "Login":
           state=value;
           return state;
        default:
          return state;
    }
}
export function userReducer(idUtente){ 
    store.userset(initalUser,"Login",idUtente);
}
export function getUser(){
    return store.getState();
}

Upvotes: 0

Views: 109

Answers (1)

phry
phry

Reputation: 44326

Honestly, pretty much everything you do here is incorrect. createStore needs to be called with the reducer, not the initial state. userset does not magically become a property of the store, and you have written it more like a reducer than an action creator - but it is not a valid reducer (that would only accept two arguments) and you have no dispatched action anywhere to be seen in that code.

So, this would need to look like

import {createStore} from "redux";

const initalUser={
    IdUtente: 0
 };

const store=createStore(
    userReducer
  )

function userReducer(state=initalUser,action){
    switch(action.type){
        case "Login":
           return action.payload;
        default:
          return state;
    }
}

export function userSet(idUtente){ 
    store.dispatch({ type: "Login", payload: idUtente });
}

export function getUser(){
    return store.getState();
}

and even that would not be very typical redux code.

Adding to all this: This is a very outdated style of redux that we are not recommending to teach or learn any more.

Please, ignore whatever tutorial you are following right now, go to the official redux tutorials at https://redux.js.org/tutorials/index and follow both of them, from beginning to end (they start with old-style redux to explain the basics and then teach you modern redux, which looks very different).

Upvotes: 2

Related Questions