Raghul Ramkish
Raghul Ramkish

Reputation: 101

React function calling and accessing variables

I am trying to access an state outside of function in React

All i am trying to do is on clicking on save i need to get all the details in form and submit through API,

The below is my full code and i have only removed the imported component details ,

What we need is when click on the save , The form should submit through the API Call

Here is my code:

**
function save() {
  let contactid=editcontacts.id;
  const updateapi=axios.create({baseURL:"https://108.248.238.235/TiaraDeskAPI/api/v1/contacts/"+contactid})
    let name = editcontacts.contact_name
    let email =editcontacts.email
    let phone = editcontacts.phone
    let address = editcontacts.address
    let city = editcontacts.city
    let state = editcontacts.state
    let country = editcontacts.country
    let pincode = editcontacts.zipcode
    let accountid=selected[0].id;
    //const notes = document.getElementById('input-notes').value
    const json={"account" : accountid,"contact_name" : name, "email" : email,"phone" :phone, "street" : address, "city" : city, "state" : state, "country" : country, "zipcode" : pincode};
    
    console.log(json);
    api.post("/",json,options).then(response => {
      console.log(response.data.message);
    
    })
}
**

const EdittableData = () => {
  const [selected, setSelected] = useState([]);
  const [lookuplist, setaccount2] = React.useState([]);
  const [editcontacts, setaccount] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const api=axios.create({baseURL:"https://18.28.238.25/TI/api/v1/contacts/1/"+contactid})
  const accountapi=axios.create({baseURL:"https://18.48.28.25/TI/api/v1/account"})
const options = {
  headers: {'Authorization': apitoken}
}
  //let id = useParams();
  console.log(params.id);
  React.useEffect(async () => {
    const response = await api.get("/",options);
    const response2 = await accountapi.get("/",options);

    setLoading(false);
  }, []); 



  if (loading) {
    return <>Loading...</>;
  }    
 
  return(
    <>
     <Form>
            
                <h6 className="heading-small text-muted mb-4">
                  Contact Information
                </h6>
                <div className="pl-lg-4">
                  <Row>
                    <Col lg="12">
                      <FormGroup>
                        <label
                          className="form-control-label"
                          htmlFor="input-username"
                        >
                          Contact Name
                        </label>
                        <Input
                          className="form-control-alternative"
                        
                          id="input-username"
                          placeholder="Username"
                          type="text"
                          defaultValue={editcontacts.contact_name}
                        />
                      </FormGroup>
                    </Col>
                 
                  </Row>
                 
               
                
                </div>
               
              </Form>
    
    </>
  ) 
 }

const Viewcontact = () => {
 
  
  return (
    <>
    
    <Header />
    {/* Page content */}
    <Container className="mt--7" fluid>
    
             

***************
                  <Button
                    color="primary"
                    href="#pablo"
                   onClick={save}
                    size="sm"
                  >
                    Edit
                  </Button>
*****************
           
       
     
      </>
  
  )};
export default Viewcontact;
```

I am trying to call function save in react and access the states but failed,

The error is , I cant able to access any states or variables, can you help me please

Thanks in advance

Upvotes: 0

Views: 56

Answers (2)

Fishu Kek
Fishu Kek

Reputation: 71

The straightforward solution is to put your save() function and your submit button (in your case 'Edit' button) inside EditableData component. It is a good practice to put your submit buttons inside forms.

const EdittableData = () => {
  const [selected, setSelected] = useState([]);
  const [lookuplist, setaccount2] = React.useState([]);
  const [editcontacts, setaccount] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const api=axios.create({baseURL:"https://18.28.238.25/TI/api/v1/contacts/1/"+contactid})
  const accountapi=axios.create({baseURL:"https://18.48.28.25/TI/api/v1/account"})
const options = {
  headers: {'Authorization': apitoken}
}
  //let id = useParams();
  console.log(params.id);
  React.useEffect(async () => {
    const response = await api.get("/",options);
    const response2 = await accountapi.get("/",options);

    setLoading(false);
  }, []); 

    function save() {
    let contactid = editcontacts.id;
    const updateapi = axios.create({
      baseURL:
        "https://108.248.238.235/TiaraDeskAPI/api/v1/contacts/" + contactid
    });
    let name = editcontacts.contact_name;
    let email = editcontacts.email;
    let phone = editcontacts.phone;
    let address = editcontacts.address;
    let city = editcontacts.city;
    let state = editcontacts.state;
    let country = editcontacts.country;
    let pincode = editcontacts.zipcode;
    let accountid = selected[0].id;
    //const notes = document.getElementById('input-notes').value
    const json = {
      account: accountid,
      contact_name: name,
      email: email,
      phone: phone,
      street: address,
      city: city,
      state: state,
      country: country,
      zipcode: pincode
    };

    console.log(json);
    api.post("/", json, options).then(response => {
      console.log(response.data.message);
    });
  }

  if (loading) {
    return <>Loading...</>;
  }    
 
  return(
    <>
     <Form>
            
                <h6 className="heading-small text-muted mb-4">
                  Contact Information
                </h6>
                <div className="pl-lg-4">
                  <Row>
                    <Col lg="12">
                      <FormGroup>
                        <label
                          className="form-control-label"
                          htmlFor="input-username"
                        >
                          Contact Name
                        </label>
                        <Input
                          className="form-control-alternative"
                        
                          id="input-username"
                          placeholder="Username"
                          type="text"
                          defaultValue={editcontacts.contact_name}
                        />
                      </FormGroup>
                    </Col>
                 
                  </Row>
                 
               
                
                </div>
                <Button color="primary" href="#pablo" onClick={save} size="sm">
                  Edit
                </Button>;
              </Form>
    
    </>
  ) 
 }

Upvotes: 0

Arya
Arya

Reputation: 124

You cannot access state of an outside component. If you wish to access state outside of component, you can check React Context (shared state for multiple components).

However, your can reconsider your approach: should you be able to call <EdittableData /> inside <Viewcontact />, you could put all your form's state and save() function inside <ViewContact /> component. Then you can pass your state down to <EdittableData> as props. This way, save() function and <EdittableData> component will have access to same state.

Upvotes: 1

Related Questions