Josh Simon
Josh Simon

Reputation: 259

Axios post method in react isn't working: suggestions?

I'm trying to update a database with a user's text input, and it isn't working, even after trying a bunch of different approaches.

The text input is controlled by the following component:

import React from 'react'


class Dogue extends React.Component {
    constructor(props){
        super(props)

        this.state = {
            id: '',
            nameInput:''
        }

        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    handleChange(e) {
        this.setState({
            id: Date.now(),
            nameInput: e.target.value
        })
    }

    handleSubmit(e){
        e.preventDefault()
       this.props.inputFunction(this.state.nameInput, this.state.id)
    }

    render(){
        console.log(this.props.id)
        return (
        <div className = 'dogue-container'>
            <img className = 'img' src = {this.props.dogList}/>
            <br/>
                <form onSubmit = {this.handleSubmit} className = 'form'>
                    <input 
                    onChange ={this.handleChange} 
                    className ='input' 
                    type = 'text' 
                    placeholder = 'Enter dog name'
                    />
                    <br/>
                    <button className = 'button'>Submit</button>
                </form>
            <h2 className = 'text'>Name: {this.props.name} </h2>
        </div>
    )
    }
}


export default Dogue

and the state update and post is controlled by the App component:


import React, { Component } from "react";
import './styles.css'
import DogList from "./DogList";
import axios from "axios";


class App extends React.Component {
  constructor() {
    super();
    this.state = {
      loading: false,
      dog: [],
      dogName: [],
      newName:''
    };
    this.updateStateWithInput = this.updateStateWithInput.bind(this)
  }

  setData = async () => {
    const x = await fetch("https://dog.ceo/api/breed/hound/images");
    const y = await x.json();
    const z = await y.message;

    let newArr = [];
    for (let i = 0; i < z.length; i++) {
      if (i <= 9) {
        newArr.push(z[i]);
      }
    }
    return newArr;
  };

  async componentDidMount() {
    this.setState({
      loading: true
    });

    let dogPromise = await this.setData();
    let dogNamePromise = await axios.get('http://localhost:3000/dogs');


    this.setState({
      loading: false,
      dog: dogPromise,
      dogName: dogNamePromise.data
    });
  }
//Here is the function to update state and make axios post

async updateStateWithInput (nameInput,id) {
  let newDog={id:id, dogName:nameInput}
  this.setState({
    dogName: this.state.dogName.push(newDog)
  })
  await axios.post('http://localhost:3000/dogs', this.state.dogName)
  .then(res => {
    console.log(res)
  })
  }

  render() {
    return this.state.loading ? (
      <h1 className = 'text'> Dogues Loading.....</h1>
    ) : (
      <div>
        <h1 className = 'text'>Rate My Dogue</h1>
        <DogList
          dogs={this.state.dog}
          name={this.state.dogName}
          inputFunction = {this.updateStateWithInput}
        />
      </div>
    );
  }
}

export default App

Basically, all I'm trying to do is update an array of objects, with a new object - example as follows:

//existing array:
[
  {
    id: 1,
    dogName: 'bruce',
  },
  {
    id: 2,
    dogName: 'borker',
  },
  {
    id: 3,
    dogName: 'henry',
  },
];

//new object to be pushed into array:

{id: id of some sort, dogName: the text input from the user}

Upvotes: 0

Views: 44

Answers (1)

Mario Vernari
Mario Vernari

Reputation: 7304

Either you use await or use then, cannot use both:

  const res = await axios.post('http://localhost:3000/dogs', this.state.dogName);
  console.log(res)

Upvotes: 3

Related Questions