asyncData not being called on refresh in a nested route - async-await

I have a blog detail page, which has a asyncData call to t he blog ID requested. When the redirection happens from index to the detail page, the asyncData requests the detail, but when I refresh the detail page there is no call made. The first code is from index.vue and the the second is the nested component.
async asyncData() {
const { data } = await axios.get(
'https://calltocms.com/_/items/blog?meta=total_count%2Cresult_count&limit=50&offset=0&fields=%2A.%2A.%2A&sort=-publishing_date'
)
return { articles: data }
}
asyncData({ params, error }) {
return axios
.get(
`https://calltocms.com/_/items/blog/${+params.id}?fields=%2A.%2A.%2A`
)
.then(res => {
return { post: res.data }
})
.catch(e => {
error({ statusCode: 404, message: 'Post not found' })
})
}
I want the asyncData call to be made on refresh from the nested component.

Related

Cancel previous call made using fetch API in Vue JS

I am working in laravel + VueJS application.In that there is a search functionality through which user can search any text then API will called to get data based on search text.So to call API in laravel "Fetch API" in VueJS is used.So now when any user press any keyword then everytime the method will be called to get the result.So due to that multiple request has been send.I just like to do that when any user type any text then everytime previous request must be cancelled.The code i have attached below which is used to call the API and fetch the data.
searchProperties(search) {
if (search != null && search != '') {
this.review = false;
this.clearSes = false;
fetch('/search/' + search)
.then(res => res.json())
.then(res => {
if (res.status === 200) {
this.properties = res.data.properties;
}
});
} else {
this.clearSuggestions();
}
}
Thanks in advance!
You could you an abortable fetch like this
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000);
fetch(url, { signal }).then(response => {
return response.text();
}).then(text => {
console.log(text);
});
See docs for more details.

laravel (with vue and vuex) overriding sendResetLinkEmail but can't pass the data to the api controller

I'm creating forgot password on my web application using laravel (with vue and vuex). I found a good tutorial (https://codebriefly.com/vue-js-reset-password-laravel-api/). I try to apply vuex on this tutorial but it not works.
Accrording to the tutorial
<script>
export default {
data() {
return {
email: null,
has_error: false
}
},
methods: {
requestResetPassword() {
this.$http.post("/reset-password", {email: this.email}).then(result => {
this.response = result.data;
console.log(result.data);
}, error => {
console.error(error);
});
}
}
}
</script>
I apply Vuex
ForgotPassword.vue
methods: {
...mapActions(["requestResetPassword"]),
request() {
this.requestResetPassword({
email: this.email
})
.then(response => {
toast.fire({
type: "success",
title: "Password reset email sent"
});
this.$router.push({ name: "home" });
})
.catch(error => {
console.error(error);
});
});
}
Vuex action that i created
requestResetPassword(data){
return new Promise((resolve,reject) => {
axios.post('/reset-password',{
email: data.email
})
.then(response =>{
resolve(response)
})
.catch(error =>{
reject(error)
})
})
}
The Api that handle
public function sendPasswordResetLink(Request $request)
{
return $this->sendResetLinkEmail($request);
}
When I input the email address for sending password reset link, the error shows up and it says:
message: The given data was invalid.
email :The email field is required.
I test the API using postman and it works
I check the input field to see if it was empty, but it turns out the input field was not empty
Is there a way to apply vuex on this tutorial ? thanks
In Postman, you are putting the email field as a param, not as serialized data in the body. The vue-resource package's post method sets the data passed to it as the body, not as URL parameters. Either add the email to the request parameters, or in your API, make sure you grabbing data from the request body and not URL parameters.

Can the completion of one async call be sequenced before the start of another using useEffect?

I'm trying to use useEffect in my React app but also refactor things more modularly. Shown below is the heart of actual working code. It resides in a Context Provider file and does the following:
1. Calls AWS Amplify to get the latest Auth Access Token.
2. Uses this token, in the form of an Authorization header, when an Axios GET call is made to an API Endpoint.
This works fine but I thought it would make more sense to move Step #1 into its own useEffect construct above. Furthermore, in doing so, I could then also store the header object as its own Context property, which the GET call could then reference.
Unfortunately, I can now see from console log statements that when the GET call starts, the Auth Access Token has not yet been retrieved. So the refactoring attempt fails.
useEffect(() => {
const fetchData = async () => {
const config = {
headers: { "Authorization":
await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert('Error getting authorization token: '.concat(error))
})
}};
await axios.get('http://127.0.0.1:5000/some_path', config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert('Error getting data from endpoint: '.concat(error));
});
};
fetchData();
}, [myContextObject.some_data]);
Is there a way of refactoring my code into two useEffect instances such that the first one will complete before the second one starts?
You could hold the config object in a state. This way you can separate both fetch calls and trigger the second one once the first one finished:
const MyComponent = props => {
const myContextObject = useContext(myContext);
const [config, setConfig] = useState(null);
useEffect(() => {
const fetchData = async () => {
const config = {
headers: {
Authorization: await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert("Error getting authorization token: ".concat(error));
})
}
};
setConfig(config);
};
fetchData();
}, [myContextObject.some_data]);
useEffect(() => {
if (!config) {
return;
}
const fetchData = async () => {
await axios
.get("http://127.0.0.1:5000/some_path", config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert("Error getting data from endpoint: ".concat(error));
});
};
fetchData();
// This should work for the first call (not tested) as it goes from null to object.
// If you need subsequent changes then youll have to track some property
// of the object or similar
}, [config]);
return null;
};

Nuxt.js and Laravel Api - 422 Displaying Error instead of Forms

[Error][1]
Hi Team,
Whenever I am receiving the error return from laravel the nuxt.js project displays the error on the page instead the HTML/Forms. How can i handle this.
Here is my php code
return response()->json([
'errors' => [
'email' => ['Sorry we cant find you with those details.'],
],
], 422);
Javascript
async submit() {
await this.$auth.loginWith("local", {
data: this.form
})
In your JavaScript you need to wrap your await promise inside a try catch block. Here's a fix for your JS.
try {
await this.$auth.loginWith("local", {
data: this.form
})
} catch (e) {
return;
}
This is an old question at this point, but I thought I'd post the full code since I was pretty stumped and didn't find many great answers out there:
async handleSubmit() {
try {
const authResponse = await this.$auth.loginWith('local', {
data: this.formData
});
const { status, data } = authResponse;
if (status === 200)
this.createFlashAlert({ 'success': 'Login successful' });
} catch (error) {
if (error.response.status === 422)
this.createFlashAlert(error.response.data);
}
}
So the checklist:
Wrap the login call in a try/catch if you're using async await syntax (be sure to make it an async function i.e. async handleSubmit.
in the catch block, use the error.response object, this is an axios thing. With this you'll be able to access the response status and data.
If you log just the error object, it's not obvious that you can access the response within that error which is what had me stumped.

302 Found on Laravel in GET request made by cross-fetch on react

I have a component with a table, when this component mounts I would like to make a request to get data that fills the table.
In my table component:
componentDidMount() {
const { fetchTransactions } = this.props;
fetchTransactions()
}
This came from (I'm using redux):
const mapDispatchToProps = dispatch => ({
fetchTransactions: value => dispatch(fetchTransactions())
})
And the action:
export function fetchTransactions() {
return function (dispatch) {
dispatch(requestTransactions())
return fetch('/getTransactions')
.then(
response => response.json(),
error => console.log('An error occurred.', error)
)
.then(json => dispatch(receiveTransactions(json)))
}
}
When the component mounts, the action is dispatched and the fetch too, but the response is a 302 found as you can see here:
Using the browser it work as I expect:
Any ideas? thank you.

Resources