1

I'm trying to save an array to state and then I want to somehow loop over the array that was saved to state in the dom to create an unordered list using one item from the array for each

  • The array values in the example below are just to make it simple, they actually come from a database and I don't know the values ahead of time, but I do know they are strings.

    import React, { useState } from 'react';
    const Worbli: React.FC = () => {
    
      const [state, setState] = useState({
         myArray = '';
      });
      const theArrayToSave = ['apple', 'orange', 'peach'] 
      setState({ ...state, myArray: theArrayToSave });
    
      return (
        <ul>
          { state.myArray.map( (fruit:string,index:number) => (<li key={index} >{fruit}</li>)) }
        </ul>
      )
    }
    

    The error I get is

    Argument of type '{ myArray: string[]; accountNameError: string; loading: boolean; }' is not assignable to parameter of type 'SetStateAction<{ accountNameError: string; loading: boolean; myArray: string; }>'.
      Type '{ myArray: string[]; }' is not assignable to type '{ myArray: string; }'.
        Types of property 'myArray' are incompatible.
          Type 'string[]' is not assignable to type 'string'.ts(2345)
    
  • 4
    • Shouldn't the initial value be an array? myArray = []; Commented Nov 7, 2019 at 14:50
    • It's still incompatible Type 'string[]' is not assignable to type 'never[]'. Commented Nov 7, 2019 at 14:52
    • 1
      It seems like you are missing a lot of typings in your code, did you exclude them for the code sample purpose or you didn't add them? Commented Nov 7, 2019 at 15:02
    • @Cristy I was just trying to simplify the code so it was easy to look at Commented Nov 7, 2019 at 15:05

    3 Answers 3

    2

    You should declare your state like this:

    const [state, setState] = useState({
      myArray: [];
    });
    

    But as you mentioned before, this makes it a never[] type instead of a string[] type and still throws an error. To solve this you should add types to your state declaration like this:

    interface IState {
      accountNameError: string;
      loading: boolean;
      myArray: string[];
    }
    
    const [state, setState] = useState<IState>({
      accountNameError: "",
      loading: false,
      myArray: []
    });
    

    This way you specifically tell TypeScript what your state value should look like.

    Sign up to request clarification or add additional context in comments.

    Comments

    1

    You have to initialize your state with an empty array instead of initializing it with a an empty string. It should work

    const [state, setState] = useState<{myArray:string[]}>({
         myArray: [];
      });
    

    2 Comments

    It's still incompatible Type 'string[]' is not assignable to type 'never[]'
    I corrected, now it should works because useState like some others React hooks use Generics, so you can use it.
    0

    First declare your useState type and set your default array like this:

    live preview example: https://codesandbox.io/s/gallant-river-p3cfl

    import React, { useState } from "react";
    import { render } from "react-dom";
    
    import "./styles.css";
    
    type IState = {
      myArray: string[];
    };
    
    const Worbli: React.FC = () => {
      const [state, setState] = useState<IState>({
       myArray: ["apple", "orange", "peach"]
      });
    
      return (
        <ul>
          {state.myArray.map((fruit: string, index: number) => (
            <li key={index}>{fruit}</li>
          ))}
         <button
           onClick={() =>
           setState({ myArray: [...state.myArray, "Random Fruit Name?"] })
         }
        >
          Add to state
      </button>
    </ul>
    );
    };
    
    const rootElement = document.getElementById("root");
    render(<Worbli />, rootElement);
    

    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.