Search code examples
reactjsaxiossetstate

How to setState, object value in the stateless component in react?


I am using a stateless component and got value from the API with Axios & useEffect(), then I have set one value in the state but I want to set response object in the state:

import React, { useState, useEffect } from "react";
import axios from 'axios';

export default function Login(props) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [userData, setUserData] = useState([]);

function validateForm() {
    return email.length > 0 && password.length > 0;
}

useEffect(()=>{
    axios.get(apiBaseUrl+'api/users')
        .then(response =>{
            // how to set my value: response.data.data
            setUserData(response.data.data);
            console.log(response.data.data);
        }, error => {
            console.log(error)
        })
},[])

Solution

  • setUserData is a function to update your userData value. The code below should do the trick

    
    const [userData, setUserData] = useState({});
    
     useEffect(()=>{
        axios.get(apiBaseUrl+'api/users')
            .then(response =>{
                // how to set my value: response.data.data
                setUserData(response.data.data)
                console.log(response.data.data)
            }, error => {
                console.log(error)
            })
    },[])