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)