How to apply a method to a string when setting state, react hooks

Viewed 385

I am trying to split a string while I am setting it. React gives error "TypeError: is undefined" if I try to apply a method to it (like string.split("_"))

But if I don't try to apply the method, the string displays correctly. Hoe can achieve applying the method before setting state?

  const [data, setData] = useState([]);
  const [photoArray, setPhotoArray] = useState([]);
  const [photoNum, setPhotoNum] = useState(0);
  const [photoName, setPhotoName] = useState("");

  useEffect( () => {
    const fetchData = async () => {
      const result = await axios(
        {
            url: 'http://localhost:1000',
            method: 'GET',
            },
        );
      const result2 = await axios(
        {
            url: 'https://someurl.com',
            method: 'GET'
        },
      )
        setData(result2.data.items)

      }
    fetchData();
  }, []);

  useEffect( () => {
    setPhotoArray(data.map( photo => photo.name))
  },[data])

  useEffect( () => {
    //This doesn't work
    setPhotoName(photoArray[0].split('_').join(' ')
    //This works:
    // setPhotoName(photoArray[0])
  },[photoArray])

Also, am I using useEffect properly? (3 times, each time waiting for one setSate to apply another)

3 Answers

You have to check for undefined, like below

useEffect( () => {
    setPhotoName(photoArray[0] ? photoArray[0].split('_').join(' ') : '')
  },[photoArray])

If you are using Typescript 3.7 or above you can use Optional Chaining and do the undefined check like this.

useEffect( () => {
    setPhotoName(photoArray?.[0]?.split('_').join(' ')
  },[photoArray])

you are missing parenthesis. try this.

setPhotoName(photoArray[0].split('_').join(' '));

I was trying to setState without, well, setState. The solution was to apply the split() method when actually setting the state of that array.

    useEffect( () => {
      setPhotoArray(data.map(photo => photo.name.split('_').join(' ')))
    },[data])

    useEffect( () => {
      setPhotoName(photoArray[0])
    },[photoArray])
Related