I am using a flask backend and react frontend to create a website and I am encountering an error when fetching a url from the backend.
the backend part has a database and returns it as a json
@app.route('/getlists', methods=['GET','POST'])
def getlists():
if request.method == 'GET':
user_id = session.get("user_id")
lists = ListOfLists.query.filter_by(user_id = user_id).all()
return jsonify(lists)
which looks like this for example:
[
{
"color": "#ffffff",
"name": "name1"
},
{
"color": "#ee3a70",
"name": "name2"
}
]
and my frontend should fetch the url from the server and display the data as a list
export default function UserPage() {
const [allValues, setAllValues] = useState({
color: '',
name: '',
});
useEffect(() => {
fetch('http://localhost:5000/getlists')
.then(response => response.json())
.then(data => setAllValues(data.color))
.then(data => setAllValues(data.name))
},[])
const ListGroupItem = (lgi, index) => {
return (
<ListGroup.Item variant="default" key={index} style={{ textAlign: 'right', color: "white", background: lgi.color }} as="li" action href="#link1" >
{lgi.title}
</ListGroup.Item>
)
};
return (...)
although whenever I try to render the list, it gives me Unhandled Rejection (TypeError):Failed to fetch
is there a problem with my code? or is there an easier way to do this?
I think that problem is, that you are using setAllValues wrong way, because there is object {color, name}
and you are setting whole state to color and then reseting to name, just try to simply set data=>setAllValues(data)
and change default state so it will be array of objects instead of just object, setState([])
.
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.