Home > front end >  Why is the state undefined in redux
Why is the state undefined in redux

Time:11-02

I am trying to get some data from a reducer in redux and when I get the state using useSelector it return undefined I have tried to use console.log to log the data as well seeking help from other stackoverflow posts can anyone help?

Thanks!

Code:

import foo from "foo";
import React from "react";
import useSelector from "react-redux";

function fooBar():React.FC {
let data = useSelector(state:StateType=>{state.fooBar});
return(
<div>
<p>{data}</p>
</div>
);
}

CodePudding user response:

With the information given, you've not returned the state value from the function body.

let data = useSelector(state:StateType=>{state.fooBar}); // <-- no return!!

You should either explicitly return state.fooBar from the function:

const data = useSelector(state: StateType => {
  return state.fooBar;
});

Or use the implicit arrow function return (notice there is no function body enclosed in { ... }):

const data = useSelector(state: StateType => state.fooBar);
  • Related