mySQL database is not fetching data in React

Issue

enter image description hereI am using React for my front end. MySQL as my database, Node JS EXpress JS for the backend and Axios as my middleware. Every thing is working fine , the admin page is working fine , the forms are sending data to the database. The problem is that I have created a page to show the messages from the database and for some reason the database is not fetching the data from the table I want. I get the error data.map() is not a function , because the data state is not being set in the axios.get() function. I have provided the code below:

Messages.js

import React , {useEffect , useState} from 'react';
import MessageCard from './MessageCard';
import ax from 'axios';
import './Messages.css';




function Messages()
{


    const [data , setData] = useState({});

    useEffect(()=>{


        ax.get('http://localhost:3001/server/message').then((response)=>{

            if(response)
            {
                setData(response.data);
            }

            console.log(response.data);

            response.data.map((element)=>{console.log(element.ID)});

        });

        console.log(1);





    } , [setData])


    return(
        <>

<div id="messageMain">
             {data.map((element)=>{return <MessageCard fullName = {element.FullName} em = {element.Email} no = {element.PhoneNumber} msg = {element.Message} />})}
            </div>

        </>
    );
}

export default Messages;

index.js (Server File)


const myServer = require('express');
const db = require('mysql');
const body_parser = require('body-parser');
const serverObj = myServer();
const cors = require('cors');



const database = db.createPool({
    host:'localhost',
    user:'root',
    password : 'apt-getinstall',
    database : 'unified_messages'
})

serverObj.use(myServer.json());
serverObj.use(cors());

serverObj.use(body_parser.urlencoded({extended:true}));

serverObj.post('/server/insert' , (req,res)=>{

    const FullName = req.body.FullName;
    const Email = req.body.Email;
    const PhoneNumber = req.body.PhoneNumber;
    const Message = req.body.Message;

    console.log(FullName);
    const insertData = 'INSERT INTO client (FullName , Email , PhoneNumber , Message) VALUES (?,?,?,?)';
    database.query(insertData , [FullName , Email ,PhoneNumber , Message ] , (err , result)=>{console.log(err)});
})


serverObj.get('/server/admin' , (req,res)=>{
    const Username = req.body.Username;
    const Password = req.body.Password;
    const getData = 'SELECT username , password FROM unified_admins;';
    var usernameD , passwordD;
    database.query(getData , (err,result)=>{ res.send(result)});
    


})

serverObj.get('/server/message' , (req,res)=>{


    const getData = 'SELECT * FROM client;';
    database.query(getData , (err,result)=>{ res.send(result); console.log(result); console.log(err);});
    


})

serverObj.listen(3001 , ()=>{console.log('Connected')} );

The network panel is shown below:
[![enter image description here][2]][2]

App.js

import React from 'react';
import {Routes , Route} from 'react-router-dom';

import Landing from './Components/Landing';
import Home from './Components/Home';
import Services from './Components/Services';
import Particlesbg from './Components/Particlesbg';
import Aboutus from './Components/Aboutus';
import Work from './Components/Work';
import Contact from './Components/Contact';
import Admin from './Components/Admin';
import Messages from './Components/Messages';


function App() {


    return (
        <>

        <Particlesbg/>
        <Routes>

            <Route exact path = "/" element = {<Landing/>} />
            <Route exact path = "/Home" element = {<Home/>} />
            <Route exact path = "/About" element = {<Aboutus/>} />
            <Route exact path = "/Services" element = {<Services/>} />
            <Route exact path = "/Contact" element = {<Contact/>} />
            <Route exact path = "/Work" element = {<Work/>} />
            <Route exact path = "/Admin" element = {<Admin/>} />
            <Route exact path = "/Messages" element = {<Messages/>} />
        </Routes>
        </>
    );
}

export default App;

Solution

First .map is an array [] method you are trying to use on an object {}. you need to change that. You need change useState({}) to useState([]).

After make sure your state is updated before trying to map it.

Here is a solution to insure there is items in your array.

 ax.get('http://localhost:3001/server/message').then((response)=>{

            if(response)
            {
                setData(response.data);
            }

            console.log(response.data);
            
            // Checks to see if there is an item in the array.
            if(data[0]){
              // Then map over array if item is in array
              response.data.map((element)=>{console.log(element.ID)});
            }

        });

Hope This helps 🙂

Answered By – Randall H

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published