This is where I'm trying to get data from back-end, using Axios requests:
const [models, setModels] = useState([]); const sponsor_id = localStorage.getItem('sponsor_id'); useEffect(() => { api.get('models', { sponsor_id }).then(response => { setModels(response.data); }); }, []);
And this is my back-end, where it was supposed to return data from database:
module.exports = { async index(request, response) { const { sponsor_id } = request.body; const models = await connection('model').select('*').where('sponsor_id', sponsor_id); return response.json(models); },
But the response on front-end is empty. It was supposed to return some data. I hope that someone can help me.
Please check this example. Here I call axios in useEffect and showing response data in ui.
import React, {useEffect, useState} from "react";
import axios from 'axios';
function PostListPage() {
const [posts, setPost] = useState([]);
let signal = axios.CancelToken.source();
useEffect(() => {
let isSubscribed = true;
axios.get(`https://jsonplaceholder.typicode.com/posts`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
return function cleanup() {
isSubscribed = false;
signal.cancel('Api is being canceled');
}
}, []);
return (
<React.Fragment>
<ul>
{
posts.map(post => <li key={post.id}>{post.title}</li>)
}
</ul>
</React.Fragment>
);
}
export default PostListPage;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.