I have a bit of code that is trying to fetch some data and save it to update a list array but is is not updating it. The code below is some hard coded array that works fine but in the second I try to fetch the data but nothing?
Any idea where I am going wrong, I am not really getting the hang of this. Thanks
The code which works :-
const data = [
{id: '1', name: 'A'},
{id: '2', name: 'B'},
{id: '3', name: 'C'},
{id: '4', name: 'D'},
{id: '5', name: 'E'}
];
export default function App() {
const [lists, setLists] = useState(data);
And what I am trying to use to fetch :
export default function App() {
const fetchURL = 'https://www.uberfantasies.com/rn.php'
const [lists, setLists] = useState('');
const getData = () =>
fetch(fetchURL)
.then((res) => res.json());
useEffect(() => {
getData().then((lists) => setLists(res.data) // If I use data it can display the hard coded array //
}, []);
What am I doing wrong?
CodePudding user response:
This will load the data once and update the list when the component mounts
const [lists, setLists] = useState('')
useEffect(() => {
const fetchURL = 'https://www.uberfantasies.com/rn.php'
fetch(fetchURL)
.then((res) => res.json())
.then((json) => setLists(json?.data))
.catch(console.warn)
}, [])
CodePudding user response:
Can you log the response of your getData function instead of setting it to state? Also can you refactor your function to something like this pls.
Also, in the useEffect function, where did that res
variable come from? I assume it should be lists
.
const getData = async () => {
const res = await fetch(fetchURL);
console.log(res);
const json = await res.json();
console.log(json);
return json;
};
useEffect(() => {
getData().then((lists) => console.log(lists));
}, [])