you are currently using react to replicate Spotify.
You are currently developing a search function and have successfully received a response.
I want to show this on the screen.
How do I solve this? Please help me.
const onClick = () => {
const inputSearchData = sessionStorage.getItem('inputData');
const inputTypeData = sessionStorage.getItem('inputType');
// console.log(inputTypeData)
axios({
headers: {
"Authorization": `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
},
method: 'GET',
url: 'https://api.spotify.com/v1/search',
params: {
q: inputSearchData,
type: inputTypeData,
},
}).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
when you get your response from your axios request you need to store it inside react state.
access this inside the return statement of the component.
That will be something like that :
const SomeComponent = () => {
const [response, setResponse] = useState();
const onClick = async () => {
const inputSearchData = sessionStorage.getItem("inputData");
const inputTypeData = sessionStorage.getItem("inputType");
await axios({
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET",
url: "https://api.spotify.com/v1/search",
params: {
q: inputSearchData,
type: inputTypeData
}
})
.then((res) => {
setResponse(res);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
{/* Access your response state over here */}
{/* That will be something like that : */}
{response.map((item, index) => {
<div key={index}>
{item.somethingFromYourData}
</div>
})}
</div>
)
};
Related
I made this custom hook.
import axios from "axios";
import Cookies from "js-cookie";
import React from "react";
const useGetConferList= () => {
let token = JSON.parse(localStorage.getItem("AuthToken"));
const Idperson = JSON.parse(Cookies.get("user")).IdPerson;
const [response, setResponse] = React.useState();
const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
.then((r) => {
setResponse(r.data.Data);
})
.catch(() => alert("NetworkError"));
};
return { fetchConfer, response };
};
export default useGetConferList;
as you can see I export the fetchConfer function. but I want to make it async. for example, calling the function and then doing something else like this:
fetchConfer(Date, Time, Id).then((r) => {
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
});
as you can see in non async situation, I can't use then.
You can try this
const fetchConfer = async (datePrensence, idInsurance, timePrensence) => {
try {
const response = await axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
setResponse(response.data.Data);
// need to return data
return response.data.Data
} catch(error) {
alert("NetworkError")
}
};
use the function in another async function
const someAsyncFunc = async () => {
// try catch
const r = fetchConfer(Date, Time, Id)
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
...
or use it how you are currently using it
Hope it helps
I'm making a custom jsx element. I want to set the element's value to data, that a fetch call returns:
const BoardPage = () => {
const id = useParams().id
fetch('http://localhost:8000/getBoardByID', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ id: id })
}).then(response => response.json()).then(data => {
console.log(data)
return (
<div>
<h1>board #{data.id}</h1>
</div>
)
})
}
export default BoardPage
In console i see an object: {id: 31, board_content: '', width: 1223, height: 2323, user_privileges: '[]'}
But i get nothing as the output
You have to perform the request inside the useEffect hook.
const MyComponent = () => {
const id = useParams().id;
const [data, setData] = useState({});
React.useEffect(() => {
fetch("http://localhost:8000/getBoardByID", {
headers: {
"Content-type": "application/json",
},
method: "POST",
body: JSON.stringify({ id: id }),
})
.then((response) => response.json())
.then((data) => {
setData(data);
});
}, []);
return (
<div>
<h1>board #{data?.id}</h1>
</div>
);
};
I am trying to authenticate the user in order to get data to use to create or update meetings later. but it full of errors.
Here I am sending Post Requests in order to get the AccessToken and then get the UserData as props.
export async function getServerSideProps(res){
const oauth = async() => {
const zoomUserData = [];
const b = Buffer.from(process.env.ZOOM_API_KEY + ":" + process.env.ZOOM_API_SECRET);
const zoomRes = await fetch(`https://zoom.us/oauth/token?grant_type=authorization_code&code=${req.body.code}&redirect_uri=${process.env.ZOOM_REDIRECT_URL}`, {
method: "POST",
headers: {
Authorization: `Basic ${b.toString("base64")}`,
},
});
const zoomData = await zoomRes.json();
const zoomUserRes = await fetch("https://api.zoom.us/v2/users/me", {
method: "GET",
headers: {
Authorization: `Bearer ${zoomData.access_token}`,
},
});
const zoomUserData = await zoomUserRes.json();
/*
Encrypt and store below details to your database:
zoomUserData.email
zoomUserData.account_id
zoomData.access_token
zoomData.refresh_token
zoomData.expires_in // convert it to time by adding these seconds to current time
*/
}
return{
props:{zoomUserData}
}
}
and then i am passing the props to a page component like that :
export default function Meeting({zoomUserData}) {
const router = useRouter();
useEffect(() => {
if (router.query.code) {
fetch('/connectZoom',
{ method: 'POST',
headers: {
'ContType': 'application/json',
},
body: JSON.stringify({ code: router.query.code }),
}).then(() => {
console.log("success")
}).catch(() => {
console.log("No!")
});
}
}, [router.query.code]);
console.log(zoomUserData)
return (
<a href={`https://zoom.us/oauth/authorize?response_type=code&client_id=${process.env.ZOOM_API_KEY}&redirect_uri=${process.env.ZOOM_REDIRECT_URL}`}>
Connect Zoom
</a>
)
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a file with form to call a submit function in another file.
And I would like to retrieve the response of the request to use it in file 1.
How can I do that ?
First file form.js
handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
newAppartement(newAppartementTableau);
const messageRequest = ??;
Second file data.js
export function newAppartement(newAppartementTableau) {
axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
You are not returning anything in your function, you're just making an axios call. To solve this add this :
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
in your first file
newAppartement(newAppartementTableau).then(res => console.log(res.data).catch(e => console.error(e));
You need to wait for the function to finish using await async:
async handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
const response = await newAppartement(newAppartementTableau);
and in second file you can return a promise like this:
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
I want to make a post request to backend with all form data.
Uploading the images i get an array with data:
const normFile = e => {
const getFileList = e.fileList.map( i => i.originFileObj);
console.log('Upload event:', getFileList);
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ images: getFileList })
})
.then(async response => {
const data = await response.json();
console.log(data, 'res data')
})
.catch(error => {
console.error('There was an error!', error);
});
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
Above is my code where i use Ant Design uploader.
But how to delete the File text before each object?
You have to use multipart/form-data header
Let's say you have an input
<input type="file" onChange={uploadFile}/>
And logical part:
uploadFile = (e) => {
const formData = new FormData();
formData.append('name_your_file', e.target.files[0])
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
})
}