getStaticProps Next JS Doesn't Work in Production - javascript

I make getStaticProps in pages, in local it's work but in production doesn't work. my code is below:
import {GetStaticProps} from 'next';
export const getStaticProps: GetStaticProps = async () => {
const res = await apiAboutV2();
const data = res ?? {};
return {
props: {about: _.result(data, 'data', {})},
revalidate: true,
};
};
interface Props {
about: any;
}
export default function About({about}: Props) {
return (
<div>
{about?.history}
</div>
)
}
anyone can suggestion for me?
edit:
export const apiAboutV2 = async () => {
const uri = `${baseUrl}/api/v2/public/about`;
const res = await axios({
method: 'GET',
url: uri,
})
.then((res) => res.data)
.catch((err) => err?.response?.data || err);
return res;
};
code above is apiAboutV2

Related

Get Promise Value (axios inside Axios) and set to Hook

I have 2 axios functions, one is to return a list of currency names and the other is to get the value of the said currencies. I need to get corresponding value of the currency unto a hook.
[currencies, setCurrencies] = useState([]);
getCurrencyNames = () =>
axios({
method: `get`,
url: `${url}/getCurrencies`
}).then(r =>
setCurrencies(r.data.map(currency => {
return {
name: currency,
value: getCurrencyValue(currency)
}
}))
);
getCurrencyValue = async (currency) => {
const data = await axios({
method: `get`,
url: `${url}/getValue/?from=PHP&to=${currency}`
}).then(r => r.data)
return data;
}
what should return is the currencies hook being filled with objects such as this:
{
name: "USD",
value: 0.020
}
but the objects returned like this:
{
name: "USD",
value: Promise
}
I've also tried setting the hook into the getCurrencyValue like this:
getCurrencyValue = async (currency) => {
axios({
method: `get`,
url: `${url}/getValue/?from=PHP&to=${currency}`
}).then(r =>
setCurrencies([
...currencies,
name: currency,
value: r.data
])
)
}
but what happens is that only the last one is set inside the hook
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [currencies, setCurrencies] = useState([]);
async function getCurrencyValue(post) {
const data = await axios({
method: `get`,
url: `https://jsonplaceholder.typicode.com/users`
}).then((r) => ({
post,
user: r.data
}));
return data;
}
function getCurrencyNames() {
return axios({
method: `get`,
url: `https://jsonplaceholder.typicode.com/posts`
}).then((r) => {
const res = Promise.all(
r.data.map(async (currency) => {
return {
name: currency,
value: await getCurrencyValue(currency)
};
})
);
return res;
});
}
useEffect(() => {
(async function () {
const data = await getCurrencyNames();
console.log(data);
console.log("fetched in useEffect");
setCurrencies(data);
})();
}, []);
return <></>;
}
export default App;
Here is the link https://codesandbox.io/s/condescending-germain-8ie8j?file=/src/App.js
Note: See in the console
It is normal that it return a promise, you have to resolve it by puting await befor the call and make the map function async:
getCurrencyNames = () =>
axios({
method: `get`,
url: `${url}/getCurrencies`
}).then(r =>
setCurrencies(r.data.map(async currency => {
return {
name: currency,
value: await getCurrencyValue(currency)
}
}))
);

Why am I getting a network error on page refresh? (get request)

I'm making a get request to an API in a useEffect(). When I navigate to the page from the homepage it loads fine, but as soon as i refresh the page http://localhost:3000/coins/coin I get a Unhandled Runtime Error: Error: Network Error.
export async function getServerSideProps({ query }) {
const id = query;
return {
props: { data: id },
};
}
function index({ data }) {
const coinURL = data.id; // bitcoin
const apiEndpoint = `https://api.coingecko.com/api/v3/coins/${coinURL}`;
const [currentUser, setCurrentUser] = useState();
const [coinData, setCoinData] = useState([]);
useEffect(() => {
const getData = async () => {
const res = await axios.get(apiEndpoint);
const { data } = res;
setCoinData(data);
};
const getCurrentUser = async () => {
const res = await axios.get(
`http://localhost:5000/api/users/${session?.id}`
);
const { data } = res;
setCurrentUser(data);
};
getData();
getCurrentUser();
}, [coinData, currentUser]);
}
Why does this happen?
I'm recommending to do something like this:
const getData = async () => {
try {
const res = await axios.get(apiEndpoint);
const { data } = res;
setCoinData(data);
} catch(err) {
console.log(err)
}
};
const getCurrentUser = async () => {
try {
const res = await axios.get(
`http://localhost:5000/api/users/${session?.id}`
);
const { data } = res;
setCurrentUser(data);
} catch(err) {
console.log(err)
}
};
useEffect(() => {
getData();
getCurrentUser();
}, [coinData, currentUser]);
if you do so, you will be able to view the exact error and fix it.

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()

Why can't I load the API?

I'm going to call the movie API using the redux in the react application.
During the process of calling the movie API using the redux-thunk,
An error occurs while calling the callAPI function on the lib/THMb path.
//movie_project/src/lib/THMb.js
import axios from 'axios';
const key = "xxxxxxx";
const url = `https://api.themoviedb.org/3/movie/now_playing?api_key=${key}&language=ko&page=1&region=KR`;
export const callAPI = async () =>{
await axios.get(`${url}`);
}
import { handleActions } from "redux-actions";
import axios from "axios";
import * as movieAPI from '../lib/THMb';
// action types
const GET_MOVIES = 'movie/GET_MOVIES';
const GET_MOVIES_SUCCESS = 'movie/GET_MOVIES_SUCCESS';
const GET_MOVIES_FAILURE = 'movie/GET_MOVIES_FAILURE';
export const getMovies = () => async dispatch => {
dispatch({ type: GET_MOVIES });
try{
const res = await movieAPI.callAPI(); // failed
dispatch({
type: GET_MOVIES_SUCCESS, // 요청 성공
payload: res.data.results, // API 요청 결과 값
})
}catch(e){
dispatch({
type: GET_MOVIES_FAILURE, // 요청 실패
payload: e,
error: true
})
throw e;
}
}
const initialState ={
movieList : [],
error: null
}
const movie = handleActions(
{
[GET_MOVIES]: state => ({
...state,
// loading..
}),
[GET_MOVIES_SUCCESS]: (state, action) => ({
...state,
movieList: action.payload,
}),
[GET_MOVIES_FAILURE]: (state, action) => ({
...state,
// loading...
})
},
initialState
)
export default movie;
enter image description here
However, no error occurs when calling url from within the getMovies function.
export const getMovies = () => async dispatch => {
dispatch({ type: GET_MOVIES }); // 요청의 시작을 알림.
try{
//const res = await movieAPI.callAPI(); // failed
// success
const res = await axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=xxxxx&language=ko&page=1&region=KR`);
dispatch({
type: GET_MOVIES_SUCCESS, // 요청 성공
payload: res.data.results, // API 요청 결과 값
})
Why do errors occur in the first case???
That's because in the first case you are not returning anything. You should try this:
export const callAPI = async () => {
let res = await axios.get(`${url}`);
return res;
}
Hope this works for you.
the error occurs in callAPI function, not in getMovies because in payload you are assuming res variable to fetch the data from it and you successfully get it in getMovies function but not in callAPI.
because you did not return anything from callAPI method that's why res variable is null and it throws the error.
just replace you callAPI function with the below code.
export const callAPI = async () =>{
const res await axios.get(`${url}`);
return res
}
hopefully, it will work just give it a try

how to properly use the async and await keywords within a map

I have the following snippet of code
export const fetchPosts = () => async dispatch => {
const res = await axios.get(`${url}/posts`, { headers: { ...headers } });
console.log(res.data);
let posts = res.data.map(p => (p.comments = fetchComments(p.id)));
console.log(posts);
dispatch({ type: FETCH_POSTS, payload: res.data });
};
export const fetchComments = id => async dispatch => {
console.log(id)
const res = await axios.get(`${url}/posts/${id}/comments'`, {
headers: { ...headers }
});
console.log("id", id);
return res.data;
};
when i console log the posts, i get 2 functions returned. what is the proper way in which i should call the fetch comments for this function to return me the desired value?
Add this:
const postsResult = await Promise.all(posts)

Categories

Resources