1

I am having issues with typescript react in when try to define a value.

Here is the error:

Argument of type '{}' is not assignable to parameter of type 'SetStateAction<boolean[]>'. Type '{}' is not assignable to type '(prevState: boolean[]) => boolean[]'. Type '{}' provides no match for the signature '(prevState: boolean[]): boolean[]'.ts(2345)

Here is my following code:

const [addButtonFruits, setAddButtonFruits] = useState([true]);

useEffect(() => {
    const initialAddButtonFruits = {};
    fruitsArray.map((each) => (initialAddButtonFruits[each] = true));
    setAddButtonFruits(initialAddButtonFruits);
  }, []); // only executed for initial rendering

2 Answers 2

2

Error message says exactly what is wrong. Your state variable addButtonFruits is a boolean array. And you are trying to assign an object to it.

Try:

    const initialAddButtonFruits = fruitsArray.map(each => true);
    setAddButtonFruits(initialAddButtonFruits);

If you want to store an object:

const [addButtonFruits, setAddButtonFruits] = useState({});

useEffect(() => {
    const initialAddButtonFruits = {};
    fruitsArray.forEach((each) => (initialAddButtonFruits[each] = true));
    setAddButtonFruits(initialAddButtonFruits);
  }, []); // only executed for initial rendering
Sign up to request clarification or add additional context in comments.

Comments

0

addButtonFruits is a boolean array. You can't assign an empty object to a boolean array variable.

const initialAddButtonFruits = [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.