I have a function that gets a list of projects from a MOCK API and I wish to get the projects list and list them inside a select dropdown using React. This is what I’ve tried and I’ve gotten stuck. Please don’t mean with the responses, I’m still new as a React Developer and I am learning as I go
import React, { useEffect, useState } from "react";
import axios from "axios";
const getProjects = () => {
axios.get('/api/projects', {
header: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
})
.then((res) => {
return res.data
})
.catch((ex) => {
console.log(ex)
})
}
const Dropdown = () => {
const [projects, setProjects] = useState([])
useEffect(() => {
getProjects()
})
return(
<div>
</div>
)
}
export default Dropdown
I’ve iterated through a couple of solutions and they all aren’t working. The API sits here
MOCK API
EDIT
this is how far I’ve progressed with the suggestions
import React, { useEffect, useState } from "react";
import axios from "axios";
const getProjects = () => {
axios.get('/api/projects', {
header: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
})
.then((res) => {
return res.data
})
.catch((ex) => {
console.log(ex)
})
}
const Dropdown = () => {
const [projects, setProjects] = useState([])
useEffect(() => {
getProjects(setProjects)
}, [])
return(
<div>
<label htmlFor="select">Class Name</label>
<select>
{projects.map(project => {
return <option key={project.id} value={project.id}>{project.name}</option>
})}
</select>
</div>
)
}
export default Dropdown
2
Answers
You don’t change the state and you do nothing with the value returned from the AJAX request. You need to use something like this:
You also need:
So the AJAX request happens only on the component mount and not on every update (which may cause an infinite loop).
You can also make the fetch into a custom hook:
your code contain more errors
for correct your code and working must follow this tips
function getProject convert him to Promise
use this sentence useEffect(function(){},[]) for calling at once
if you use promise getProject then put data response in right place setProject(data.response)