koko ka
koko ka

Reputation: 117

Get the error of a JSON Validation List in ReactJS

On my api test, it was able to run as the image below. but, when I try to code in React.JS, the user Id cannot be pass in. What is the problem of this?

enter image description here

But when I try to code in front end, the user Id cannot be pass in to api. Consider the code below:

  constructor (props){
    super(props);
    const Users_id = localStorage.getItem('id');
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
    this.create = this.create.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  create(){
    // const loginEmail = localStorage.getItem('loginEmail');
    const Users_id = localStorage.getItem('id');
    this.setState({Users_id})
    // console.log(loginEmail)
    PostData('api/event/submit', this.state).then ((result) => {
        let responseJSON = result;
        console.log(responseJSON);
        console.log(this.state)

      });
   }

The error show in console.log(responseJSON): enter image description here

//Updated PostData

    return new Promise((resolve, reject) => {
        fetch( BaseUrl+type, {
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // mode: 'no-cors',
            headers: 
                { 
                    'Content-Type': 'application/json' 
                },
          })
        .then((response) => response.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });

Upvotes: 0

Views: 73

Answers (2)

fadi omar
fadi omar

Reputation: 768

you need to check if the user id exists in local storage before inserting it into props

    super(props);
    const Users_id = localStorage.getItem('id') || '';
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }

and when you want to setState you need to pass the same name you used in the state

const Users_id = localStorage.getItem('id');
if(Users_id){
this.setState({users_id: Users_id})
}

Upvotes: 1

Jacob
Jacob

Reputation: 926

Storage.getItem returns a string. The id should be casted to a number

const Users_id = parseInt(localStorage.getItem('id'));

You may want to check isNaN(Users_id) before sending it. Or just let it fail, and handle the error.

Upvotes: 1

Related Questions