skip to Main Content

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


  1. 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:

    import React, { useEffect, useState } from "react";
    import axios from "axios";
    
    const getProjects = (done) => {
        axios.get('/api/projects', {
            header: {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            }
        })
        .then((res) => {
            done(res.data);
        })
        .catch((ex) => {
            console.log(ex);
        });
    };
    
    const Dropdown = () => {
        
        const [projects, setProjects] = useState([]);
    
        useEffect(() => {
            getProjects(setProjects);
        });
    
        
        return (
          <div>
            <select>
             {projects.map(project => {
                return (
                  <option key={project.id} value={project.id}>
                    {project.name}
                  </option>
                );
             })}
            </select>
           </div>
        );
    };
    
    export default Dropdown
    

    You also need:

        useEffect(() => {
            getProjects(setProjects);
        }, []);
    

    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:

    const useProjects = () => {
        const [projects, setProjects] = useState([]);
    
        useEffect(() => {
          axios.get('/api/projects', {
            header: {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            }
          })
          .then((res) => {
            setProjects(res.data);
          })
          .catch((ex) => {
            console.log(ex);
          });
        }, []);
    
        return projects;
    };
    
    const Dropdown = () => {
        const projects = useProjects();
        
        return (
          <div>
            <select>
             {projects.map(project => {
                return (
                  <option key={project.id} value={project.id}>
                    {project.name}
                  </option>
                );
             })}
            </select>
           </div>
        );
    };
    
    Login or Signup to reply.
  2. your code contain more errors

    1. function getProject is still wait response the when use return will get undefined or null
    2. in useEffect you will give you error,because have unlimited run project
    3. after call function dont put data response in right place

    for correct your code and working must follow this tips

    1. function getProject convert him to Promise

    2. use this sentence useEffect(function(){},[]) for calling at once

    3. if you use promise getProject then put data response in right place setProject(data.response)

    if you still have any question or help i’m here you must notify me also if you need correct code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search