DEV Community

Patryk Orlik
Patryk Orlik

Posted on

React-Rails app - How to validate uniqueness?

Hi there,
This is my first post. Please let m know if I'm doing something wrong. I am Ruby on Rails deveoloper which start to useing React form Model View and Ract-Native.

I am building app to mangaing warehouse. It is already done and in production (created with Rails, Turbolinks and jQery). Now I would like to change this app to React single page app with react-native mobile version.

I knew basics about, React, Redux, React-Native now and I started changing process.

I have simple react-rails app created. I created a form in react and db in rails and I would like to crate record only if his name is unique.

I connect with rails through axios and when I try to create record with not unique name, axios send back to react action validation error.

// ACTION
export const startAddingLocation = ( name ) => {

return(dispatch) => {

const location = { name }

return axios.post( '/api/locations', { location })
.then(response => {
if(response.data['status'] === 'SUCCESS'){
const id = response.data.data.id;

const created_at = response.data.data.created_at;

dispatch(addLocation({id, ...location, created_at}));

}
else{
dispatch(nameChangedError(name, response.data['message']));
}
}).catch(error => {
dispatch(nameChangedError(name, error+"Cannot save in DB"))
});
}
}

I need to find a way to not redirect from from when have a validation error. What is the best route to do this? I tried to redirect when action nameChangedError fill up error in redux but this is asynch action and when when I am checking error in component it still empty. Sould I redirect somehow from action?

//COMPONENT ON SUBMIT
onButtonPress() {

const { name, error } = this.props;

if(name && name.length < 30){

this.props.startAddingLocation(name);

if(!error){
this.props.history.push('/locations');
}
}else{
this.props.nameChangedError(name, "Incorrect value")
}

Thanks!

Top comments (1)

Collapse
 
andy profile image
Andy Zhao (he/him)

Hey Patryk, congrats on your first post! I'd recommend using codeblocks to format your post. You can use them by wrapping your code portions in triple backticks, like so:

codeblock example

You can also put in the language you want to add syntax highlighting for, like I did with the first set of triple backticks (`javascript `).