0

Expected result: create fake API --> call function save--> method POST --> save object time to this.state.resul --> save db.json todos id 2

I'm using the library Fake an API with JSON Server.

db.json

{
  "todos": [
    {
      "id": 1,
      "title": "AAAA"
      "results": [
        {
          "time": "09:10:01",
          "desc": "bbbbb"
        },
        {
          "desc": "gfgfgfgffg",
          "time": "21:30:06"
        }
      ]
    },
    {
      "id": 2,
      "title": "BBBBBBB",
      "results": [
        {
          "time": "09:10:01",
          "desc": "reerrererer",
        },
        {
           "desc": "dfdfdfdfdfdfdfdfdfdfdf",
          "time": "21:30:06"
        }
       ]
      }
     }   

Todos

class Todos extends Component {
  constructor (props) {
  super(props);
     this.state = {
     todos: []
   }
 }

  componentDidMount() {
    axios.get("http://localhost:3000/todos")
      .then(response => {
        this.setState({
          todos: response.data
        });
      })
      .catch(error => {
        console.log('Error);
      }
    );
  }

  render () {
     return(
 )      
}
 }
export default Todos;

StopWatch

class StopWatch extends Component {
  constructor() {
   super();

    this.state = {
      resul: []
    };

  }


  save = () => {
     const resul = this.state.resul;
     this.clock = {
      clock: this.clock
    }
    resul.push(this.clock);

    this.setState({
       resul
    });

    axios.post(`http://localhost:4000/todos/2`, {
      results: this.clock
    })
     .then(function (response) {
      console.log(response);
     })
     .catch(function (error) {
       console.log(error);
    });
  }
  }


render () {
   return (
      <ul className="results">


        {
          this.state.resul
            .map((item, index) => 
              <Time 
                key= {index}
              />
            )
        }
      </ul> 
     );
  }
}


export default StopWatch;

1 Answer 1

1

Use put to update the array, and pass the whole object you want to update.

save = () =>{
  const resul = JSON.parse(JSON.stringify(this.state.resul));

  this.clock = {
    clock: this.clock
  };
  resul.push(this.clock);

  this.setState({
    resul
  });

  const todo = {
    id: 2,
    title: 'BBBBBBB',
    results: resul
  };

  axios
    .put(`http://localhost:4000/todos/2`, todo)
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.