I get these error. what do i do?
`
import React, { useState } from "react";
import "./App.css";
import { Button } from "@mui/material";
//declaring the colors
const colorSequence = [
{ "color": "#3db44b" },
{ "color": "#bfef45" },
{ "color": "#42d3f4" },
{ "color": "#4263d8" },
{ "color": "#f68232" },
{ "color": "#fee118" },
{ "color": "#e6194a" },
{ "color": "#f032e6" },
{ "color": "#921eb3" }
]
function App() {
const [colors, setColors] = useState([])
//shuffle the colors
const shuffleColors = () => {
const shuffledColors = [...colorSequence]
.sort(() => Math.random() - 0.5)
.map((color) => ({ ...color, id: Math.random() }))
setColors(shuffledColors)
}
setColors(shuffledColors) returns an error of
Argument of type '{ id: number; color: string; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'. Type '{ id: number; color: string; }[]' is not assignable to type 'never[]'. Type '{ id: number; color: string; }' is not assignable to type 'never'.ts(2345)
[![enter image description here](https://i.stack.imgur.com/1nWXL.png)](https://i.stack.imgur.com/1nWXL.png)
CodePudding user response:
You're missing the type definition of the colors
stateful variable.
const [colors, setColors] = useState<{ color: string, id: number }[]>([]);
CodePudding user response:
Argument of type '{ id: number; color: string; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'
You are missing the type when setting the state.
const [colors, setColors] = useState<{ color: string; id?: number }[]>([]);
CodePudding user response:
You're missing the type definition of the colors state variable.To solved this error there is two way.
1st way
const [colors, setColors] = useState<{ color: string, id: number }[]>([]);
2nd way
Follow Below 2 steps:
make one interface of colors like below.
interface colors {
color: String,
id: Number
}
Assign interface to the state.
const [colors, setColors] = useState< colors >([])