Home > Software design >  Creating Array out of comma seperated list in React JS
Creating Array out of comma seperated list in React JS

Time:09-03

I have an input for users to come and paste one id or multiple with each seperated by a comma then run a function on the individual Id's.

<Input type={'text'} placeholder="Id(s) (seperated by comma if more than 1)" value={ids} onChange={(event) => setIds(event.target.value)} />

Then I have the React useState constants for using the individial ids

    const [ids, setIds] = useState(["ID#1", "ID#2"]).split("[\\s,] ")
    const [id, setId] = useState(addresses[0]);

Here is where I set the function for picking each individual ID and running the function

    const fetchNft = async (e) => {
        for(let i = 0; i< ids.length; i  ){
        const _id = id[i]
        const idInfo = await find(_id);
        console.log(idInfo)
           }
}

CodePudding user response:

This doesn't make any sense:

useState(["ID#1", "ID#2"]).split("[\\s,] ")

useState returns an array containing the state value and the setter function for the state value. There's nothing to "split", and in this case neither of those values are strings.

You probably meant to put that split logic here:

setIds(event.target.value.split("[\\s,] ")

Since the input value is the string of comma-separated values that you want to split into an array.

CodePudding user response:

This can't possibly work

    const [ids, setIds] = useState(["ID#1", "ID#2"]).split("[\\s,] ")

You need to first call useState and then split on the first returned value. You can't split the return value of useState given that it is an array.

  • Related