Home > database >  React-Redux useSelector() not returning the entire string
React-Redux useSelector() not returning the entire string

Time:09-13

I have some values stored in my Redux global store. However, when I try to retrieve it's values, I get only the first character. I need the entire string from the redux store.

My redux store:

path(pin):"https://dog.ceo/api/breed/collie/border/images"
breed(pin):"collie"
subBreed(pin):"border"

My code:

  const [breed, setBreed] = useSelector((state) => state.breed);
  const [subBreed, setsubBreed] = useSelector((state) => state.subBreed);

  React.useEffect(() => {
    console.log("Breed in useEffect: ", breed);
    console.log("subBreed in useEffect: ", subBreed);
  }, [breed, subBreed]);

The console output:

Breed in useEffect:  c
subBreed in useEffect:  b

CodePudding user response:

Issue

You are using destructuring assignment to grab out individual characters from a string.

const [breed, setBreed] = useSelector((state) => state.breed);
const [subBreed, setsubBreed] = useSelector((state) => state.subBreed);

Here breed and subBreed are the first character from each character array, or string.

const [breed, setBreed] = "collie";

console.log({ breed }); // "c" from "collie"

Solution

The useSelector hook only returns the state you select, not an array of state and setter. Just assign the selected values to breed and subBreed.

const breed = useSelector((state) => state.breed);
const subBreed = useSelector((state) => state.subBreed);

or

const { breed, subBreed } = useSelector((state) => state);
  • Related