1

I'm using React with Typescript and want to add uid to dataId array. this is my code.

type ElementData = {
  uid: string;
  description: string;

}

const Modal:React.FC<Props>= (props) => {
  const [chipsState, setChipsState] = useState(false);
  const [dataId, setDataId] = useState([]);
  
  const onChipClick = (element:ElementData) => {
   setChipsState(chipsState => !chipsState);  
   setDataId(dataId => [...dataId , element.uid]);
  }
 
  return (
    <div>
    
    </div>
  );
}

export default Modal;

in this case, the following error show up with setDataId(dataId => [...dataId , element.uid]) here.

Argument of type '(dataId: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type '(dataId: never[]) => string[]' is not assignable to type '(prevState: never[]) => never[]'.
    Type 'string[]' is not assignable to type 'never[]'.
      Type 'string' is not assignable to type 'never'.

Please help me to fix this error. Thank you.

3
  • 1
    What's the type of setDataId? Also are you aware that in setDataId(dataId => [...dataId , element.uid]) you're taking an argument named dataId - which overwrites the binding to dataId outside. So the dataId you have inside this callback is not the same as the one outside. Is the callback to setDataId even supposed to take an argument? Commented May 3, 2021 at 7:23
  • Also note that [] has type never[], you may want to type that more strictly using as Commented May 3, 2021 at 7:26
  • oh, I did mistake. changed setDataId(preveId => [...preveId , element.uid]). Thank you. Commented May 3, 2021 at 7:35

1 Answer 1

1

Actually your initial state is an empty array so TS cannot infer type of dataId as array of strings, you can define type of state as:

const [dataId, setDataId] = useState<string[]>([]);
Sign up to request clarification or add additional context in comments.

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.