use axios in getStaticProps in next js - javascript

i have a next project.in this project i used axios for send and recieved request data.
but i have a problem when i use axios in getStaticProps function i get an error in my index.js page
this is my index.js
import axios from "axios";
const Home = (props) => {
console.log(props);
return <div>d</div>;
};
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
return {
props: {
data: res
}
};
}
export default Home;
and this is my index.js page in my browser
I would be very grateful if anyone could help me

it worked
try {
const result = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const data = result.data;
return {
props: {
data: data
}
}
} catch (error) {
console.log(error);
}

You should use res.data. Next time, I recommend to use console.log(res) and see the object that you receive

Add JSON.stringify when calling an asynchronous function that returns an object.
Try modifying the getStaticProps function like this:
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const stringRes = JSON.stringify(res);
return {
props: {
data: stringRes
}
};
}
OR
Use .text() to convert the response data to text like this:
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1').lean();
const textRes = await res.text();
return {
props: {
data: textRes
}
};
}

Related

How to return value from Promise in variable in a React component?

I'm currently working on a React project. Using the Axios library, I need to get data from the API and write it to a variable.
Searching the web for this, I found the only option is via Promise.then(), but that's not what I want, as the result is simply returned to the next Promise.then().
I need Axios to return the result and after that my function returns this result instead of with the tag so to speak. Sample code below. Thanks in advance.
function getData() {
let packsId = '11111';
if (packsId) {
return axios.get('http://localhost:8000/api/words?id=' + packsId)
.then((response) => {
return response.data.title;
})
.catch((error) => {
return error.code;
});
}
else {
return "Doesn't exist";
}
}
export default function WordsPack() {
let result = getData(); // here returned Promise, not String
return <div>{ result }</div>
}
If you wanna call let result = getData() at the top level of your component as you showed in your example, you would wanna transform getData to a custom hook, as an example like so:
import { useState, useEffect } from "react";
// ⚠️ Notice it start with "use":
export default function useGetData() {
const [result, setResult] = useState("Loading..."); // the data to show while fetching
useEffect(() => {
let packsId = "11111";
if (packsId) {
axios
.get("http://localhost:8000/api/words?id=" + packsId)
.then((response) => setResult(response.data.title))
.catch((error) => setResult(error.code));
} else {
setResult("Doesn't exist");
}
}, []);
return result;
}
export default function WordsPack() {
let result = useGetData();
return <div>{result}</div>
}
you need to use Async/Await
async function getData() {
let packsId = '11111';
if (packsId) {
try{
return await axios.get('http://localhost:8000/api/words?id=' + packsId);
}
catch(ex){
//error handle
}
}
else {
return <div>Doesn't exist</div>;
}
}
now to read the value you have to call with await in the same way
export default async function WordsPack() {
let result = await getData(); // here returned Promise, not Object with data
return <div>{ result }</div>
}
if it's inside component where you are calling getData()
use useEffect and implement with state
export default async function WordsPack() {
const [result, setResult] = useState();
useEffect(() => {
(async() => {
const dataResult = await getData();
setResult(dataResult)
})();
})
return <div>{ result }</div>
}
for more references you can read
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

How to split axios functions and components in vue3?

I think it is better to split the axios commands and the vue components.
This is my directory structure:
src
api
- products.js
components
- Products.vue
products.js
import axios from 'axios';
const listProducts = () => {
const headers = { "Content-Type": "application/json" };
let url = "http://localhost:8001/api/v1/products";
const response = axios.get(url, headers);
return response.data
}
export default {
listProducts,
}
Products.vue:
<template>
<div>{{ products }}</div>
</template>
<script>
import { listProducts } from "#/api/products.js"
export default {
data () {
return {
products: {},
}
},
created() {
this.getProducts();
},
methods: {
getProducts() {
this.products = listProducts();
}
}
}
</script>
But this.products is undefined. I tried some stuff with async and await, but nothing works.
And what would be best practice in vue3?
axios.get() returns a Promise, so response in the following line is actually a Promise (not the Axios response itself):
const listProducts = () => {
⋮
const response = axios.get(url, headers);
return response.data // ❌ `response` is a `Promise`
}
To get the response, you can await the result of the axios.get() call:
👇
const listProducts = async () => {
⋮ 👇
const response = await axios.get(url, headers);
return response.data
}
Similarly, this updated listProducts() function now returns a Promise because it's async. Your component now must await the result of listProducts():
// Products.vue
export default {
⋮
methods: {
👇
async getProducts() {
👇
this.products = await listProducts();
}
}
}
demo

How can I use redux saga function action inside getServerSideProps function of nextjs

in next.js, i want to operate the saga function inside getServerSideProps, it is dispatched to the serverSide store, but there is a problem that it is not shared to the client store when the hydrate action is executed. My guess is that rehydrate runs before takeEvery runs, is it a version issue?
I want to move the asynchronous logic to sagaFunction and handle it.
it's my code
//saga.ts
export function* getProductDetailSaga({ payload }: ReturnType<typeof getProductDetailAction>) {
try {
const { data } = yield* call(getProductDetail, payload);
yield put(setFetchedProductDetails(data.productDetail));
} catch (error) {
console.error(error);
}
}
export default function* productDetailSaga() {
yield all([
takeEvery(getProductDetailAction.type, getProductDetailSaga),
}
//[productId].tsx
export const getServerSideProps = wrapper.getServerSideProps((store) => async (ctx) => {
const { productId } = ctx.query;
const {
osCode,
deviceId,
session,
} = store.getState().user;
store.dispatch(
getProductDetailAction({
osCode,
deviceId,
session,
productId,
})
);
store.dispatch(END);
await store.sagaTask.toPromise();
});
i think END action and sagaTask are not functioning properly.
but this works fine.
export const getServerSideProps = wrapper.getServerSideProps((store) => async (ctx) => {
const { productId } = ctx.query;
const { osCode, deviceId, session } = store.getState().user;
const { data } = await getProductDetail({
osCode,
deviceId,
session,
productId,
});
store.dispatch(setFetchedProductDetails(data.productDetail || null));
});

useQuery doesn't return the data and the function is returned

I'm trying to get the list of the chats in my app using react-query(useQuery). my API call is in a different component and I'm using Axios to get the data. but the component is returning the function itself not the data .which part is Wrong?
import { useQuery } from "react-query";
import axios from "axios";
const getContacts = async () => {
const headers = { Authorization: localStorage.getItem("token") };
const options = {
method: "GET",
url: "http://127.0.0.1:8000/chat/mine/",
headers: headers,
};
const { data } = await axios.request(options);
return data;
};
function GetUserDataUseQuery() {
return useQuery("getContacts", getContacts);
}
export default GetUserDataUseQuery;
function getUserData() {
const data = GetUserDataUseQuery;
return (dispatch) => {
dispatch({
type: GET_CONTACTS,
payload: [],
});
};
}
I suggest you refactor your code a little to fix some of your problems:
const getContacts = async () => { /*...*/ }
const useGetContacts = () => {
return useQuery('getContacts', getContacts)
}
// `useGetContacts` is a hook, so it should be called inside of a
// component or another hook - you *cannot* call a hook inside of a
// simple function, which is what you're attempting to do inside `getUserData`
function MyComponent() {
const contacts = useGetContacts();
// ...
}
Alternatively, if you do want to use getContacts as if it was a function, then simply don't wrap it inside a useQuery, since that's what turns it into a hook.
async function getUserData() {
const data = await getContacts()
// ...
}

Return Data from Axios

I am trying to return the response from an axios API call. I don't quite get what a promise is and all the tutorials/information I find they only log the response, I want to return it.
Here is what I have, but when I call getPokemon it's undefined.
const axios = require('axios');
const getPokemon = () => {
axios.get('https://pokeapi.co/api/v2/pokemon/')
.then(function (response) {
console.log("Response:", response.data.results);
return response.data.results;
})
.catch(function (error) {
return null;
});
}
export {getPokemon};
If this is a React app then you want to do your Axios call in componentDidMount. Axios automatically returns a promise.
class Example extends Component {
constructor(props) {
super(props);
this.state = {
data: ""
};
}
componentDidMount() {
axios
.get("https://pokeapi.co/api/v2/pokemon/")
.then(res => {
console.log(res);
this.setState({
data: res.data.results
});
})
.catch(err => {
console.log(err);
});
}
render() {
let pokemon = this.state.data;
let display = Object.values(pokemon).map((item, key) => {
return (
<div>
<p>{item.name}</p>
<p>{item.url}</p>
</div>
);
});
return (
<div>{display}</div>
);
}
}
export default Example;
Doing it like this will send the Axios request after the React app has loaded and set the JSON data in the component state. You should be able to access the JSON data via this.state.data.
Check out this Codepen example with working API call.
Well, first of all, I suggest you read about promises.
a good method for achieving what you need is by using async/await syntax check out the following code:
const axios = require('axios');
const getPokemon = async () => {
try{
let res = await axios.get('https://pokeapi.co/api/v2/pokemon/');
return res.data.results;
}
catch(error){
return null //that's what you did in your code.
}
}
export {getPokemon};
Remove ".result"
const axios = require("axios");
const getPokemon = async () => {
try {
let res = await axios.get("https://jsonplaceholder.typicode.com/users");
return res.data; **here remove his .result**
} catch (error) {
return null; //that's what you did in your code.
}
};
export default getPokemon;
In index.js or any page call it:
import getPokemon from "./GetPokimon";
const xyz = async () => {
const data = await getPokemon();
alert(JSON.stringify(data));//u will see the data here
}
xyz(); //calling getPokemon()

Categories

Resources