C Sharper
C Sharper

Reputation: 8626

React Js : .map is not a function

I have json array as below -

[{"sup_Id":6,"sup_ShortCode":"A"},{"sup_Id":7,"sup_ShortCode":"B"},{"sup_Id":8,"sup_ShortCode":"C"},{"sup_Id":1000,"sup_ShortCode":"D"}]

React component reading this array as -

import React,{useEffect,useState} from 'react'
import axios from 'axios';
function AllSuppliers() {
    const [suppliers, setstate] = useState([])
    useEffect(() => {
        // GET request using axios inside useEffect React hook
        axios.get('http://localhost:62815/api/values/GetAllSuppliers')
            .then(x => setstate({suppliers:x.data}))
            .catch(error => {
                alert(error);
                
            });;
    }, []);
    return (
        <>
            <table style={{width: '50%'}}>
            <thead>
                <tr>
                <th>
                    Supplier Id
                </th>
                <th>
                    Supplier Name
                </th>
                
                </tr>
                </thead>
                {
                   
                    suppliers.map((supplier)=>supplier)
                }
            </table>
        </>
    )
}

export default AllSuppliers

I am getting -

TypeError: suppliers.map is not a function

error

I also tried with - suppliers[0].map since its an array. But this also did not worked.

Upvotes: 1

Views: 2485

Answers (3)

Yahav
Yahav

Reputation: 146

You are setting your suppliers state to be an object in this line:

.then(x => setstate({suppliers:x.data}))

Instead, let the setstate handle the change of suppliers and only pass the variable like this:

.then(x => setstate(x.data))

assuming x.data is an array.

You can also change the following line suppliers.map((supplier)=>supplier) to (suppliers || []).map((supplier)=>supplier) this way in case x.data or suppliers get changed to null\undefined your app will not crash.

Also as mentioned above the usage of setstate is not recommended. I'd advise you read about this topic here: https://reactjs.org/docs/hooks-state.html

Upvotes: 2

NeERAJ TK
NeERAJ TK

Reputation: 2695

Update the useState initialization as :

const [suppliers, setSuppliers] = useState([])

(It is more meaningful)

Also, Update the useEffect as :

useEffect(() => {
        axios.get('http://localhost:62815/api/values/GetAllSuppliers')
            .then(x => setSuppliers(x.data))
            .catch(error => {
                alert(error);
            });;
    }, []);

You need not set the state in an object when using React Hooks unlike normal class state.

Upvotes: 1

Surya
Surya

Reputation: 546

Use this way as you are using Hooks

setstate(x.data)

instead of this way which uses in class component

setstate({suppliers:x.data})

Upvotes: 1

Related Questions