when i use fetch to bring the list of notes and consol.log it nothing shows up. The url is not wrong i have carefully checked it. Here is the code:
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect(() => {
}, [])
let getNotes = async () => {
let response = await fetch('http://127.0.0.1:8000/api/notes/')
let data = await response.json()
console.log(data)
setNotes(data)
}
return (
<div>
</div>
)
}
export default NotesListPage
here is the api part:
#api_view(['GET'])
def getNotes(request):
notes = Note.objects.all()
serializer = NoteSerializer(notes, many=True)
return Response(serializer.data)
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect(() => {
getNotes();
}, [])
let getNotes = async () => {
let response = await fetch('http://127.0.0.1:8000/api/notes/')
let data = await response.json()
console.log(data)
setNotes(data)
}
return (
<div>
</div>
)
}
export default NotesListPage
You are not calling your function 'getNotes'
The way I would do it, it to fetch your data in the Effect hook and set it in your state hook there.
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect( async () => {
const response = await fetch('http://127.0.0.1:8000/api/notes/')
.then(response => response.json())
setNotes(response)
}, [])
console.log(notes)
return (
<div>
</div>
)
}
export default NotesListPage
*Edit
Cleaner would be to have the fetch in a seperate function doing the same thing and just calling that function in your effect hook (see other answer above*)
Related
**the code below is my context which I am using useFetch **
**when i change the url with changing the searchTerm **
** i am getting an infinite loop **
import React, { useContext, useState, useEffect } from "react";
import { useFetch } from "../hooks/useFetch";
const context = React.createContext();
const AppProvider = ({ children }) => {
let url = " https://www.thecocktaildb.com/api/json/v1/1/search.php?s=";
let [searchTerm, setSearchTerm] = useState("a");
useFetch(`${url}${searchTerm}`);
setSearchTerm('s');
return <context.Provider value={"hello"}>
{children}
</context.Provider >
}
const useGlobal = () => {
return useContext(context);
}
export { AppProvider, useGlobal };
** the code below is my custom hook useFetch**
`
import { useEffect, useState } from "react";
export const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const getData = async () => {
try {
const response = await fetch(url);
const jsonResponse = await response.json();
setData(jsonResponse);
setLoading(false);
} catch (err) {
console.log(err);
}
}
useEffect(() => {
getData();
}, [url])
return { data, loading };
}
`
I tried to change the search Term like this
searchTerm="h"
and it works perfectly but when i change searchTerm with setSearchTerm it gives me infinite loop
setSearchTerm('s'); inside a useEffect
const [url] = useState(" https://www.thecocktaildb.com/api/json/v1/1/search.php?s=");
const [searchTerm, setSearchTerm] = useState("a");
const { data, loading } = useFetch(`${url}${searchTerm}`);
useEffect(() => {
setSearchTerm('s');
}, [])
I'm trying to render multiple cards by pulling data from the API. But the return is an array, I don't understand why the map is not working.
const CharacterCard = () => {
const [showModal, setShowModal] = useState(false)
const openModal = () => {
setShowModal(prev => !prev)
}
const characters = useRequestData([], `${BASE_URL}/characters`)
const renderCard = characters.map((character) => {
return (
<CardContainer key={character._id} imageUrl={character.imageUrl}/>
)
})
return (
<Container>
{renderCard}
<ModalScreen showModal={showModal} setShowModal={setShowModal} />
</Container>
)
}
export default CharacterCard
The hook is this
import { useEffect, useState } from "react"
import axios from "axios"
const useRequestData = (initialState, url) => {
const [data, setData] = useState(initialState)
useEffect(() => {
axios.get(url)
.then((res) => {
setData(res.data)
})
.catch((err) => {
console.log(err.data)
})
}, [url])
return (data)
}
export default useRequestData
console error image
requisition return image
API: https://disneyapi.dev/docs
Looks like the default value of the characters is undefined.
So something like (characters || []).map.. will help I think.
For deeper look at this you can debug useRequestData hook, as I can't see the source of that hook from you example
I want my React.js page to reload after hitting the submit button. This is because I put new entries into my database and once submitting was successful, I want to request new data from the database and display them.
import React, {useEffect, useState} from 'react';
import axios from "axios";
const Questionnaire = () => {
const [questions, setQuestions] = useState({questions: []});
const [updated, setUpdated] = useState(false); // approach 1
// let updated = false // approach 2
const onSubmit = async (answeredQuestions) => {
let data = Object.values(answeredQuestions)
axios.put('http://localhost:8000/questionnaire/', data)
.then(response => {
// setUpdated(false); // approach 1
// updated = !updated; // approach 2
}
);
};
useEffect( () => {
axios.get('http://localhost:8000/questionnaire/', {})
.then((response) => {
setQuestions({"questions": response.data});
setUpdated(true); // approach 1
});
}, [updated]);
return (
<>
<Questions questions={questions} onSubmit={onSubmit} />
</>
);
}
export default Questionnaire;
I want the useEffect() to be executed immediately after getting the response from axios.put() so that the new questions can be requested and displayed to the user.
I tried out two approaches, but either axios.get() was executed twice or the re-render didn't work properly.
I appreciate your support!
Use location.reload(); after put/post request is finished as below
import React, {useEffect, useState} from 'react';
import axios from "axios";
const Questionnaire = () => {
const [questions, setQuestions] = useState({questions: []});
const [updated, setUpdated] = useState(false); // approach 1
// let updated = false // approach 2
const onSubmit = async (answeredQuestions) => {
let data = Object.values(answeredQuestions)
axios.put('http://localhost:8000/questionnaire/', data)
.then(response => {
//The below line will force browser refresh
location.reload();
}
);
};
....
//the rest of the codes
Updated answer.
It seems that your logic for approach 1 is not completely correct. Try this instead
import React, {useEffect, useState} from 'react';
import axios from "axios";
const Questionnaire = () => {
const [questions, setQuestions] = useState({questions: []});
const [updated, setUpdated] = useState(true); // Set to true to trigger get on first render
const onSubmit = async (answeredQuestions) => {
let data = Object.values(answeredQuestions)
axios.put('http://localhost:8000/questionnaire/', data)
.then(response => {
setUpdated(true); // approach 1
}
);
};
useEffect( () => {
if (updated) {
axios.get('http://localhost:8000/questionnaire/', {})
.then((response) => {
setQuestions({"questions": response.data});
setUpdated(false); // approach 1
});
}
}, [updated]);
return (
<>
<Questions questions={questions} onSubmit={onSubmit} />
</>
);
}
export default Questionnaire;
Old answer:
Is there any reason why you need to get data in a useEffect? Or could you simply do the get-request whenever the put is resolved?
import React, {useEffect, useState} from 'react';
import axios from "axios";
const Questionnaire = () => {
const [questions, setQuestions] = useState({questions: []});
const onSubmit = async (answeredQuestions) => {
let data = Object.values(answeredQuestions)
axios.put('http://localhost:8000/questionnaire/', data)
.then(response => {
axios.get('http://localhost:8000/questionnaire/', {})
.then((response) => {
setQuestions({"questions": response.data});
});
}
);
};
return (
<>
<Questions questions={questions} onSubmit={onSubmit} />
</>
);
}
export default Questionnaire;
(Or do it with async/await since you are declaring onSubmit to be an async function)
i am creating a custom hook in React, this is my code:
import {useEffect} from 'react';
const useFetch = (url) => {
useEffect(() => {
const fetchData = () => {
const data = url + "TEST";
return data;
}
fetchData();
})
}
export default useFetch;
It now returns some dummy value but that is just because of testing purposes.
Here is where i invoke my custom hook:
const Data = useFetch("https://customapiurlrandom.com/");
useEffect(() => {
console.log(Data);
}, [])
The thing is, when i check my console i see undefined. And i can't find out why.
Any ideas? Thanks in advance.
Your custom hook didn't return anything. You should add a state to keep the value and return it
import {useEffect, useState} from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = () => {
const data = url + "TEST";
return data;
}
setData(fetchData());
},[url, setData]);
return data;
}
export default useFetch;
And then use like this
const Data = useFetch("https://customapiurlrandom.com/");
useEffect(() => {
console.log(Data);
}, [Data])
I'm new to ReactJS, please don't judge me.
So I fetch some user and I want to display them one by one, but as you can see in this picture I don't get the ID, but I get the id in the iteration
import React, { useState, useEffect } from 'react';
import '../App.css';
import { Link } from 'react-router-dom';
function Users() {
useEffect(() => {
fetchItems();
}, []);
const [items, setItems] = useState([]);
const fetchItems = async () => {
const data = await fetch('https://jsonplaceholder.typicode.com/users');
const items = await data.json();
console.log(items.id);
setItems(items);
};
return (
<div>
{items.map(item => (
<h1 key={item.id}>
<Link to={`/users/${item.id}`}>{item.name}</Link>
</h1>
))}
</div>
);
}
export default Users;
and here is my UserDetails :
import React, { useState, useEffect } from 'react';
import '../App.css';
function UserDetail({ match }) {
useEffect(() => {
fetchItem();
console.log(match.id);
}, [match]);
const [user, userItem] = useState({});
const fetchItem = async () => {
const data = await fetch(
`https://jsonplaceholder.typicode.com/users/${match.id}`
);
const user = await data.json();
console.log(user);
};
return (
<div>
<h1>Item</h1>
</div>
);
}
export default UserDetail;
and i get this error.
I dont' get my id,and i don't know why.