How do I bind the function and button together in reactjs

Viewed 58

I made a button which should save the post when it's clicked. It calls a function when it gets clicked but I think it's not passing the states properly or maybe the binding has not worked properly, I don't have any idea where it went wrong. I hope someone can correct me on this.

The error it is currently showing are:

Line 12: 'title' is not defined no-undef

Line 12: 'description' is not defined no-undef

Line 12: 'id' is not defined no-undef

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";


const savepost = async () => {
  const post = { ...title, ...description, ...id };
  const request = {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    }
  };
  if (post.id == null) delete post.id;
  try {
    const response = await fetch("/api/updateposts", {
      ...request,
      body: JSON.stringify(this.state)
    });
    const data = await response.json();
    if (data.status == 200) {
      console.log("success", "post saved successfully!");
    } else {
      console.log(
        "danger",
        "An error has occured while updating the post. Please try again"
      );
    }
  } catch (ex) {
    console.error(ex.stack);
    console.log(
      "danger",
      "An error has occured while updating the post. Please try again"
    );
  }
};


export default class MainText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      description: "",
      id: ""
    };
  }

  render() {
    return (
      <>
              <Link to="/about">
                <Button className="btn savebtn" onClick={savepost}>
                  Save <i className="fas fa-save" />
              </Link>
      </>
3 Answers

Okay you are not passing any arguments to your function First pass arguments as

return (
  <>
          <Link to="/about">
            <Button className="btn savebtn" 
             onClick={() => savepost({ ...this.state})}>
              Save <i className="fas fa-save" />
          </Link>
  </>
  )

Then in your function get these as

const savepost = async ({ title, description, id}) => {
  const post = { title, description,id };
  ... // remaining code 
}

Hope it helps

You must have to pass state to the function , because it is not accessible to your function unless you pass it like this :

<Link to="/about">
  <Button className="btn savebtn" onClick={() => savepost(this.state)}>
    Save <i className="fas fa-save" />
  </Button>
</Link>


const savepost = async (props) => {
   const post = { props.title, props.description, props.id };
}

I've made a StackBlitz about this, but first thing is that you're not passing any parameters to your savepost function (When it needs 3 - title, description, and id). Hope this helps, Regards.

Related