Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
ReactJS - Setting state with multiple JSON-objects, keeps returning undefined/non-changed

So I am trying to set the state with the objects in getMatchesByDogId. But Res1 & Res2 keeps returning undefined, and the state only returns the values from initialState (unchanged).

I will be getting data from DB through axios later, and the format looks like this:

{ "body": { "id": 5, "name": "Enya", "gender": "Female" "user": { "id": 3, "firstName": "Tim" } } }

I thought that I might be getting the path wrong when assigned the data in name: res.name, so I tried name: res.body.name, name: res.data.body.name - But none of these solutions were successful. I have researched, although I'm obviously searching for the wrong information.

What am I doing wrong? Thank you.

import React, { Component } from "react";

export default class Matching extends Component{

    constructor(props) {
        super(props);
        this.getMatchesByDogId = this.getMatchesByDogId.bind(this);
        this.state = {
            items: [
                this.initialState
            ]
        }
    };

        initialState = {
            body: {
                name: "Initial",
                gender: "Initial",
                user: {
                    id: "Initial",
                    firstName: "Initial"
                }
            }
        }

    async getMatchesByDogId(){

                const dummyData = [
                    {body: {name: "Enya", gender: "Female",
                            user: {id: 1, firstName: "Tim"}}
                    },
                    {body: {name: "Fido", gender: "Male",
                            user: {id: 1, firstName: "Steve"}}
                    },
                    {body: {name: "Spike", gender: "Male",
                            user: {id: 2, firstName: "Dude"}}
                    },
                    {body: {name: "Lassie", gender: "Female",
                            user: {id: 3, firstName: "Lisa"}}
                    }
                ]

                return dummyData;
    }

    async componentDidMount() {

    console.log("Res1: ", res.data)

        this.getMatchesByDogId().then((res) => {
            this.setState({
                    body : {
                        name: res.name,
                        gender: res.gender,
                        user: {
                            id: res.id,
                            firstName: res.firstName
                        }
                    }
            });

      console.log("Res2: ", res.name)

        })

      console.log("State: ", this.state);

    };
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The getMatchesByDogId method is returning an array not a single entry. If you want to add the array to your state you can just do something like the following

  this.getMatchesByDogId().then((res) => {
            this.setState({
                    items: res
            });

Since you're just returning the array there's also no res.data prop. This prop is only part of axios response (https://axios-http.com/docs/res_schema)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda