React TypeError: orders.map is not a function - react-redux

I'm a begginer in React. I'm trying to fetch an array of data about orders and that is working and then map it to display specific information about each order.
I'm getting TypeError: orders.map is not a function exception in my application.
Here's my code:
class Orders extends Component {
state = {
orders: []
};
componentDidMount() {
axios
.get("https://localhost:9090/orders")
.then(res => {
this.setState({ orders: res.data });
console.log(res.data);
});
}
render() {
const { orders } = this.state;
const orderList =
this.state.orders.length > 0 ? (
orders.map(o => {
return (
<div key={o.orderId}>
<p>
{o.isbn}
</p>
</div>
);
})
) : (
<div className="row p-5 m-5">
<div className="offset-sm-5 col-sm-2 text-center">
<span className="text-grey r">Loading...</span>
</div>
</div>
);
return <div className="container">{orderList}</div>;
}}
What's interesting, I have a similar code, that is working. The only difference is basically what it's fetching. Here's the code:
class BookList extends Component {
state = {
books: []
};
componentDidMount() {
console.log(this.props.match.params.search_term);
axios
.get("https://localhost:8080/search?searchTerm=" + search_term)
.then(res => {
this.setState({ books: res.data });
console.log(res.data);
});
}
render() {
const { books } = this.state;
const booksList =
this.state.books.length > 0 ? (
books.map(b => {
return (
<div key={b.isbn} className="card">
<div className="card-body">
<h5 className="card-title">
<Link to={"/details/" + b.isbn}>{b.title}</Link>
</h5>
<div className="card-subtitle text-muted">
{b.author} ({b.year}) /{" "}
<span className=" text-danger">{b.category}</span>
</div>
<p />
</div>
</div>
);
})
) : (
<div className="row p-5 m-5">
<div className="offset-sm-5 col-sm-2 text-center">
<span className="text-grey r">Loading...</span>
</div>
</div>
);
return <div className="container">{booksList}</div>;
}}
I can't find the difference that would cause that exception. It is an array in both cases.
Any suggestions?
EDIT:
here's the output of response data:
response data of order
response data of bokstore

From them images it looks like the orders are processed as plain text and not parsed to JSON. Check that your back-end specifies the required headers Content-Type: application/json so that axios will parse the data correctly.
Alternatively you could parse the text client-side with JSON.parse(res.data)

Related

GraphQL mutation on Form Click not triggering

I am trying to call Apollo Mutation Hook on form submit to create a new record in the database.
export default function NewJobForm() {
const { loading, error, data } = useQuery(GET_LOC_CAT_TYPE_QUERY);
const [newJob] = useMutation(NEW_JOB_MUTATION);
const [remote, setRemote] = useState(false);
const editorRef = useRef(null);
const log = () => {
if (editorRef.current) {
console.log(editorRef.current.getContent());
}
};
let initialFormValues = {
companyName: '',
title: '',
};
const JobSchema = yup.object({
companyName: yup.string().required('Please enter the company name.'),
title: yup.string().required('Please enter the job title.'),
});
let formValidate = (values) => {
console.log(values);
const errors = {};
return errors;
};
let handleError = (field, actions) => {
field.forEach((data) => {
let field = data.param;
switch (field) {
// case 'name':
// actions.setFieldError('name', data.msg);
// break;
default:
break;
}
});
};
let formSubmit = async (values, actions) => {
console.log(values);
newJob({ variables: values });
};
return (
<>
<Formik
validationSchema={JobSchema}
validate={(values) => formValidate(values)}
onSubmit={(values, actions) => formSubmit(values, actions)}
enableReinitialize={true}
initialValues={initialFormValues}
validateOnChange={true}
validateOnBlur={false}
>
{({ handleSubmit, setFieldValue, values }) => (
<form noValidate onSubmit={handleSubmit}>
<div className="space-y-8 divide-y divide-gray-200">
<div>
<div>
<h3 className="text-lg font-medium leading-6 text-gray-900">
Job Details
</h3>
<p className="mt-1 text-sm text-gray-500">
This information will be displayed
publicly so be careful what you share.
</p>
</div>
<div className="grid grid-cols-1 mt-6 gap-y-6 gap-x-4 sm:grid-cols-6">
<div className="sm:col-span-4">
<TextInput
label="Company Name"
id="companyName"
name="companyName"
type="text"
placeholder="eg: Google"
helpText="Please Enter the name of the company"
/>
</div>
<div className="sm:col-span-4">
<TextInput
label="Job Title"
id="title"
name="title"
type="text"
/>
</div>
</div>
</div>
</div>
</form>
)}
</Formik>
</>
);
}
On Form Submit the console.log displays the message but the mutation network call does not seem to get triggered.

How to Display search result on another page in react hooks

I m developing an e-commerce application with react hooks in search component result is shown beneath the component I want to render on search Result component how to redirect search result on the search Result component
import React, { useState, useEffect } from "react";
import { Link, Redirect } from "react-router-dom";
import { getCategories, list } from "./apiCore";
import SearchResult from "./SearchResult";
const Search = () => {
const [data, setData] = useState({
categories: [],
category: "",
search: "",
results: [],
searched: false,
});
const { categories, category, search, results, searched } = data;
const loadCategories = () => {
getCategories().then(data => {
if (data.error) {
console.log(data.error);
} else {
setData({ ...data, categories: data });
}
});
};
useEffect(() => {
loadCategories();
}, []);
const searchData = () => {
// console.log(search, category);
if (search) {
list({ search: search || undefined, category: category }).then(
response => {
if (response.error) {
console.log(response.error);
} else {
setData({ ...data, results: response, searched: true });
}
}
);
}
};
const searchSubmit = e => {
e.preventDefault();
searchData();
};
const handleChange = name => event => {
setData({ ...data, [name]: event.target.value, searched: false });
};
const searchMessage = (searched, results) => {
if (searched && results.length > 0) {
return `Found ${results.length} products`;
}
if (searched && results.length < 1) {
return `No products found`;
}
};
const searchedProducts = (results = []) => {
return (
<div>
<h2 className="text-muted mb-4">
{searchMessage(searched, results)}
</h2>
<div className="row">
{results.map((product, i) => (
<CarouselCard key={i} product={product} />
))}
</div>
</div>
);
};
return (
<div className="site-navbar-top">
<div className="container">
<div className="row align-items-center">
<div className="col-6 col-md-4 order-2 order-md-1 site-search-icon text-left">
<form className="site-block-top-search" onSubmit={searchSubmit}>
<span className="icon icon-search2"></span>
<input type="text" className="form-control border-0" placeholder="Search" onChange={handleChange("search")} />
</form>
</div>
<div className="col-12 mb-3 mb-md-0 col-md-4 order-1 order-md-2 text-center">
<div className="site-logo">
<Link to="/" className="js-logo-clone">Shoppers</Link>
</div>
</div>
<div className="col-6 col-md-4 order-3 order-md-3 text-right">
<div className="site-top-icons">
<ul>
<li><Link to="#"><span className="icon icon-person" /></Link></li>
<li><Link to="#"><span className="icon icon-heart-o" /></Link></li>
<li>
<Link to="cart.html" className="site-cart">
<span className="icon icon-shopping_cart" />
<span className="count">2</span>
</Link>
</li>
</ul>
</div>
</div>
</div>
</div>
{searchedProducts(results)}
</div>
)
}
export default Search;
The main part of the hook is pretty straightforward, but I'm having a difficult time finding a nice way to handle that redirect. The current working solution is to wrap the functional component with withRouter, then pass props.history

Laravel & Vue.js. I Can't Fix My Code

I'm working on an application to manage some Cvs.
All my resource functions work perfectly (creating and editing new Cvs etc.)
But in my Vue.js part, it's about showing details for every Cv in a show view using Axios to get data from the database or post using a form.
My console shows a reactivity problem about my variables: infos and info.
Here is my show.blade.php code:
#extends('layouts.app')
#section('content')
<div class ="container" id="app">
<div class="container" id="app">
<div class ="row">
<div class="col-md-12">
<div class="panel-panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-md-18"> <h3 class="panel-title"> Experience </h3></div>
<div class="col-md-2 text-right">
<button class="btn btn-success" > Ajouter</button>
</div>
</div>
</div>
<div class="panel-body" >
<ul class="list-group">
<li class="list-group-item" v-for="info in infos">
<div class="pull-right">
<button class="btn btn-warning btn-sm">Edit</button>
</div>
<h3>#{{ info.titre }}</h3>
<p>#{{ info.body }}</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div >
<form class="flex flex-col" #submit.prevent="addExperience">
<textarea class="border rounded p-2 mp-3" v-model="info.titre"></textarea>
<textarea class="border rounded p-2 mp-3" v-model="info.body"></textarea>
<button type="submit" class="border rounded py-2">Commenter</button>
</form>
</div>
</div>
</div>
#endsection
#section('javascripts')
<script src="{{ asset('js/vue.js')}}"> </script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
window.Laravel={!! json_encode([
'csrfToken' => csrf_token(),
'idExperience' => $id,
'url' =>url('/')]) !!} ;
</script>
<script>
var app= new Vue({
el:'#app',
data:{
message: '',
infos: [],
info:{
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
}},
methods:{
getExperiences: function() {
axios.get(window.Laravel.url+'/getexperiences/'+window.Laravel.idExperience)
.then(response=>{
console.log(reponse.data);
this.info=reponse.data;})
.catch(error =>{
console.log('errors: ', error);})},
addExperience:function(){
axios.post(window.Laravel.url+'/addexperience', this.info)
.then(repsonse => {
if(response.data.etat){
this.infos.unshift(this.info);
this.info={
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
};}})
.catch(error =>{
console.log('errors: ', error)})},
created:function(){
this.getExperiences();})};
</script>
#endsection
And my two functions get Experiences and addExperience in CvController:
public function getExperiences($id){
$cv= Cv::find($id);
return $cv->infos;
}
public function addExperience(Request $request){
$info = new Info;
$info->titre=$request->titre;
$info->body=$request->body;
$info->cv_id=$request->cv_id;
$info->save();
return response()->json(['etat'=> true, 'id'=> $info->id]);
}
And these are my routes:
Route::resource('cvs','CvController');
Route::get('/getexperiences/{id}', 'CvController#getExperiences');
Route::post('/addexperience', 'CvController#addExperience');
My console:
There are some syntax errors that need to be fixed first.
There's an extra ")" at the end of your created method
The methods property is missing a closing "}"
There's a missing ")" at the very end to match the opening new Vue( parenthesis.
It's helpful to indent your code to make these things easier to spot.
Then, you'll need to update your data to be a function that returns an object. See Vue Docs - Data Must Be a Function
You also have some typos for the "response" variable.
Lastly, in your HTML you have two divs that have id="app".
Your JS should look something like:
var app = new Vue({
el: '#app',
data: {
message: '',
infos: [],
info: {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
}
},
methods: {
getExperiences: function () {
axios.get(window.Laravel.url + '/getexperiences/' + window.Laravel.idExperience)
.then(response => {
console.log(reponse.data);
this.info = response.data;
})
.catch(error => {
console.log('errors: ', error);
})
},
addExperience: function () {
axios.post(window.Laravel.url + '/addexperience', this.info)
.then(response => {
if (response.data.etat) {
this.infos.unshift(this.info);
this.info = {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
};
}
})
.catch(error => {
console.log('errors: ', error)
})
},
created: function () {
this.getExperiences();
}
}
});
Let me know if that works for you.

No error messages from 422 response on laravel form request from vue component

I'm trying to submit a form request using axios, have it validated, and return errors if the validation fails. The problem is, when I submit the form, no error messages are returned for me to show on the client side. Here's the HTTP request and vue component:
<div class="card">
<div class="card-header">
<h4>Information</h4>
</div>
<div class="card-body">
<p v-if='!isEditMode'><strong>Name:</strong> {{businessData.name}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-name">Name</label></strong>
<input class="form-control" name="business-name" v-model='businessData.name'>
</div>
<p v-if='!isEditMode'><strong>Description:</strong> {{businessData.description}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-description">Description</label></strong>
<textarea class="form-control normal" name="business-description"
placeholder="Enter your services, what you sell, and why your business is awesome"
v-model='businessData.description'></textarea>
</div>
</div>
</div>
<div class="card">
<h4 class="card-header">Address Information</h4>
<div class="card-body">
<p v-if="!isEditMode"><strong>Street Address: </strong> {{businessData.street}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-street">Street Address: </label></strong>
<input type="text" class="form-control" name="business-street" v-model='businessData.street' placeholder="1404 e. Local Food Ave">
</div>
<p v-if="!isEditMode"><strong>City: </strong> {{businessData.city}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-city">City: </label></strong>
<input class="form-control" type="text" name="business-city" v-model='businessData.city'>
</div>
<p v-if="!isEditMode"><strong>State: </strong> {{businessData.state}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-state">State: </label></strong>
<select class="form-control" name="business-state" id="state" v-model="businessData.state" >...</select>
</div>
<p v-if="!isEditMode"><strong>Zip: </strong> {{businessData.zip}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-zip">Zip: </label></strong>
<input class="form-control" type="text" maxlength="5" name="business-zip" v-model='businessData.zip'>
</div>
</div>
</div>
<div class="card">
<h4 class="card-header">Contact Information</h4>
<div class="card-body">
<p v-if="!isEditMode"><strong>Phone: </strong> {{businessData.phone}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-phone">Phone: </label></strong>
<input class="form-control" type="tel" name="business-phone" v-model='businessData.phone'>
</div>
<p v-if="!isEditMode"><strong>Email: </strong> {{businessData.email}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-Email">Email: </label></strong>
<input class="form-control" type="email" name="business-email" v-model='businessData.email'>
</div>
</div>
</div>
</div>
<script>
export default {
data () {
return {
isEditMode: false,
businessData: this.business,
userData: this.user,
errors: []
}
},
props: {
business: {},
user: {},
role: {}
},
//Todo - Institute client side validation that prevents submission of faulty data
methods: {
validateData(data) {
},
saveBusinessEdits () {
axios.put('/businesses/' + this.business.id , {updates: this.businessData})
.then(response => {
console.log(response.data)
// this.businessData = response.data;
this.isEditMode = false;
})
.catch (response => {
console.log(response.data)
this.isEditMode = false;
})
},
saveUserEdits () {
axios.put('/profile/' + this.user.id , {updates: this.userData})
.then(response => {
console.log(response.data)
this.userData = response.data;
this.isEditMode = false;
})
.catch (response => {
console.log(response)
this.isEditMode = false;
})
}
}
}
Route
Route::put('/businesses/{id}', 'BusinessesController#update');
BusinessController and update function
public function update(BusinessRequest $request, $id)
{
$business = Business::find($id)->update($request->updates);
$coordinates = GoogleMaps::geocodeAddress($business->street,$business->city,$business->state,$business->zip);
if ($coordinates['lat']) {
$business['latitude'] = $coordinates['lat'];
$business['longitude'] = $coordinates['lng'];
$business->save();
return response()->json($business,200);
} else {
return response()->json('invalid_address',406);
}
$business->save();
return response()->json($business,200);
}
and BusinessRequest class
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric',
];
}
public function messages() {
return [
'business-zip.min:5' =>'your zip code must be a 5 characters long',
'business-email.email'=>'your email is invalid',
'business-phone.numeric'=>'your phone number is invalid',
];
}
}
I don't understand why, even if input valid data, it responds with a 422 response and absolutely no error messages. Since this is laravel 5.6, the 'web' middleware is automatic in all of the routes in the web.php file. So this isn't the problem. Could anyone help me normalize the validation behavior?
In Laravel a 422 status code means that the form validation has failed.
With axios, the objects that are passed to the then and catch methods are actually different. To see the response of the error you would actually need to have something like:
.catch (error => {
console.log(error.response)
this.isEditMode = false;
})
And then to get the errors (depending on your Laravel version) you would have something like:
console.log(error.response.data.errors)
Going forward it might be worth having a look at Spatie's form-backend-validation package
You can use Vue.js and axios to validate and display the errors. Have a route called /validate-data in a controller to validate the data.
app.js file:
import Vue from 'vue'
window.Vue = require('vue');
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
class Errors {
constructor() {
this.errors = {};
}
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
record(errors) {
this.errors = errors;
}
clear(field) {
delete this.errors[field];
}
has(field) {
return this.errors.hasOwnProperty(field);
}
any() {
return Object.keys(this.errors).length > 0;
}
}
new Vue({
el: '#app',
data:{
errors: new Errors(),
model: {
business-name: '',
business-description: '',
business-phone: ''
},
},
methods: {
onComplete: function(){
axios.post('/validate-data', this.$data.model)
// .then(this.onSuccess)
.catch(error => this.errors.record(error.response.data.errors));
},
}
});
Make a route called /validate-data with a method in the controller, do a standard validate
$this->validate(request(), [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric'
]
);
Then create your inputs in your view file, using v-model that corresponds to the vue.js data model fields. Underneath it, add a span with an error class (basic red error styling, for example) that only shows up if the errors exist. For example:
<input type="text" name="business-name" v-model="model.business-name" class="input">
<span class="error-text" v-if="errors.has('business-name')" v-text="errors.get('business-name')"></span>
Don't forget to include the app.js file in footer of your view file. Remember to include the tag, and run npm run watch to compile the vue code. This will allow you to validate all errors underneath their input fields.
Forgot to add, have a buttton that has #onclick="onComplete" to run the validate method.

VueJs component: can't attribute axios reponse to a component variable

I am new to VueJs with Laravel. I have a component called Event in which a 'read more...' link shoud trigger a function that fetch the event infos from the data base and store the in a variable withing this same component.
Here is the code for my component:
<template>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h5>
Title: {{ event.event_name }}
<span class="pull-right">
#click=getEventInfo(event.id)>Read more ...</a></span>
</h5>
<h5>publised by: {{ event.user.name }}
<span class="pull-right" v-text="timeFromNow(event.created_at)"></span>
</h5>
</div>
<div class="panel-body">
<p>{{ event.event_detail }}</p>
</div>
<div class="panel-footer">
<p>
<span>Event for: {{ event.event_to_whom }}</span>
<span>When: {{ dayOfDate(event.event_when_date) }} {{ event.event_when_date }} at {{event.event_when_time}}</span>
</p>
</div>
</div>
</div>
</template>
<script>
import moment from 'moment';
export default {
name: 'app-event',
props:['event'],
data() {
return {
eventInfo: {}
}
},
methods: {
timeFromNow(tmp) {
return moment(tmp).fromNow();
},
dayOfDate(d) {
let dt = moment(d, "YYYY-MM-DD");
return dt.format('dddd');
},
//event.id
getEventInfo(id){
let url = 'events/' + id;
axios.get(url)
.then((response) => {
console.log(response.data); //returns data
this.eventInfo = response.data;
console.log(this.eventInfo);//returns data
});
console.log(this.eventInfo); //returns nothing
}
}
}
</script>
The problem is when I click the 'read more...' link axios returns a response that I can check using console.log(response.data). Hovever when I console.log(this.eventInfo) outside the axios closure, it returns and ampty object.
Am I doing something wrong? Sorry if the question is too basic.
Thanks
L.B
You are printing logging the property before it is assigned a value.
The code below should resolve any errors
import moment from 'moment';
export default {
name: 'app-event',
props:['event'],
data() {
return {
eventInfo: {}
}
},
methods: {
timeFromNow(tmp) {
return moment(tmp).fromNow();
},
dayOfDate(d) {
let dt = moment(d, "YYYY-MM-DD");
return dt.format('dddd');
},
//event.id
getEventInfo(id){
let url = 'events/' + id;
axios.get(url)
.then((response) => this.handleResponse(response.data));
},
handleResponse(eventInfo) {
console.log(eventInfo);
// do something with the eventInfo...
}
}
Your axios call is asynchrone so your outside console.log will be process before the return of the response.
Just keep your code in the .then((response) => { // here i proceed the read more }

Resources