This is a continuation of yesterday’s post on React. As today’s lesson is a lab (code-along), the post will not be comprehensive.
Form Validation using Joi:
Joi-browser
import joi from “joi-broswer”
schema = {_id:Joi.string(),.integer().min(1).required(),imageUrl:Joi.string().uri({relativeOnly:true}).required()};
validateForm= () => {const options= { abortEarly:false };const result=Joi.validate(this.state.data, this.schema, options);console.log(result.error);return result.error;};
Create a validateField:
validateField= (inputName, value) => {constschema= { [inputName]:this.schema[inputName] };constresult=Joi.validate({ [inputName]:value }, schema);returnresult.error;};
Note: We did not use Joi.object because we needed to change the schema later on, and Joi.object is immutable.
Testing
expect(getByText(“Save”)).toHaveAttribute(“disabled”);
because HTML will either disabled or not
because HTML will either disabled or not
React Fetch
React app — Client <-(request, response)-> external API server (using express js, node js) <– DB (mongoDB: mongoose + ORM)
Load restaurants on component “mounted”:
componentDidMount() {constid=this.props.match?this.props.match.params.id:null;constrestaurantFound=getRestaurants().find(restaurant=>restaurant._id===id);if (!restaurantFound) return;constnewRestaurant= { …restaurantFound };newRestaurant.cuisineId=newRestaurant.cuisine._id;deletenewRestaurant.cuisine;this.setState({ data:newRestaurant });}