Why can't I load the API? - javascript

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

Related

getStaticProps Next JS Doesn't Work in Production

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

React context returns promise

I have a todo app. Im trying to use context api(first time). I have add, delete and get functions in context. I can use add and delete but cant return the get response to state. It returns promise if i log; context. Im using async await. I tried almost everything i know but cant solve it. Where is my fault ?
Thank you.
task-context.js
import React, { useReducer } from "react";
import TaskContext from "./task-actions";
import { TaskReducer, ADD_TASK, GET_TASKS, REMOVE_TASK } from "./reducers";
const GlobalState = (props) => {
const [tasks, dispatch] = useReducer(TaskReducer, { tasks: [] });
const addTask = (task) => {
dispatch({ type: ADD_TASK, data: task });
};
const removeTask = (taskId) => {
dispatch({ type: REMOVE_TASK, data: taskId });
};
const getTasks = () => {
dispatch({ type: GET_TASKS });
};
return (
<TaskContext.Provider
value={{
tasks: tasks,
getTasks: getTasks,
addTask: addTask,
removeTask: removeTask,
}}
>
{props.children}
</TaskContext.Provider>
);
};
export default GlobalState;
reducers.js
import taskService from "../Services/tasks-service";
export const ADD_TASK = "ADD_TASK";
export const GET_TASKS = "GET_TASKS";
export const REMOVE_TASK = "REMOVE_TASK";
const addTask = async (data, state) => {
console.log("Adding : " + data.title);
try {
let task = {
title: data.title,
description: data.description,
comment: data.comment,
progress: data.status
};
const res = await taskService.addNewTask(task);
console.log(res);
if (res) {
getTasks();
}
} catch (err) {
console.log(err);
}
return;
};
const getTasks = async () => {
let response = {}
try {
const res = await taskService.loadTasks();
response = res.data
} catch (err) {
console.log(err);
}
return { tasks: response }
};
const removeTask = async (data) => {
try {
await taskService.deleteTask(data.id);
} catch (err) {
console.log(err);
}
};
export const TaskReducer = (state, action) => {
switch (action.type) {
case ADD_TASK:
return addTask(action.data);
case GET_TASKS:
console.log(getTasks());
return getTasks();
case REMOVE_TASK:
return removeTask(action.data);
default:
return state;
}
};
task-actions.js
import React from "react";
export default React.createContext({
addTask: (data) => {},
removeTask: (data) => {},
getTasks: () => {}
});
To start with, you are getting promises returned because you are explicitly returning promises: return addTask(action.data). All your actions are returning promises into the reducer.
A reducer should be a pure function, meaning that it does not have any side effects (call code outside its own scope), or contain any async functionality, and it should return the same data given the same inputs every single time. You've essentially got the workflow back to front.
There's a lot to unpick here so I'm going to provide pseudocode rather than try and refactor the entire service, which you will have a more complete understanding of. Starting with the reducer:
export const TaskReducer = (state, action) => {
switch (action.type) {
case ADD_TASK:
return [...state, action.data];
case GET_TASKS:
return action.data;
case REMOVE_TASK:
return state.filter(task => task.id !== action.data.id);
default:
return state;
}
};
This reducer describes how the state is updated after each action is complete. All it should know how to do is update the state object/array it is in charge of. When it comes to fetching data, calling the reducer should be the very last thing you have to do.
Now on to the actions. The add action is a problem because its not actually returning any data. On top of that, it calls getTasks when really all it ought to do is return one added task (which should be getting returned from await taskService.addNewTask). I would expect that res.data is actually a task object, in which case:
export const addTask = async (data) => {
try {
const task = {
title: data.title,
description: data.description,
comment: data.comment,
progress: data.status
};
const res = await taskService.addNewTask(task);
return res.data;
} catch (err) {
return err;
}
};
Similarly for getTasks, I'm going to assume that await taskService.loadTasks returns an array of task objects. In which case, we can simplify this somewhat:
export const getTasks = async () => {
try {
const res = await taskService.loadTasks();
return res.data;
} catch (err) {
return err;
}
};
Your removeTask action is essentially fine, although you will want to return errors instead of just logging them.
Notice we're now exporting these actions. That is so we can now call them from within GlobalState. We're running into issues with name collision so I've just underscored the imported actions for demo purposes. In reality, it might be better to move all the functionality we did in the last step into your taskService, and import that straight into GlobalState instead. Since that's implementation specific I'll leave it up to you.
import {
TaskReducer,
ADD_TASK,
GET_TASKS,
REMOVE_TASK,
addTask as _addTask,
getTasks as _getTasks,
removeTask as _removeTask,
} from "./reducers";
const GlobalState = (props) => {
const [tasks, dispatch] = useReducer(TaskReducer, { tasks: [] });
const addTask = async (task) => {
const added = await _addTask();
if (added instanceof Error) {
// handle error within the application
return;
};
dispatch({ type: ADD_TASK, data: added });
};
const removeTask = async (taskId) => {
const removed = await _removeTask(taskId);
if (removed instanceof Error) {
// handle error within the application
return;
};
dispatch({ type: REMOVE_TASK, data: taskId });
};
const getTasks = async () => {
const tracks = await _getTracks();
if (tracks instanceof Error) {
// handle error within the application
return;
};
dispatch({ type: GET_TASKS, data: tracks });
};
...
}
Hopefully now you can see how the workflow is supposed to progress. First we call for data from our backend or other API, then we handle the response within the application (for instance, dispatching other actions to notify about errors or side effects of the new data) and then finally dispatch the new data into our state.
As stated at the beginning, what I've provided is essentially pseudocode, so don't expect it to work out of the box.

How to return an array received from fetching api data in a .then statement?

I'm trying to export an array inside a .then statement but its not working. I have no clue how to make it work otherwise. Actually I'm just trying to set my initial state in redux to this static data I am receiving from the movie database api.
import { API_URL, API_KEY } from '../Config/config';
const urls = [
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`,
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=2`,
]
Promise.all(urls.map(items => {
return fetch(items).then(response => response.json())
}))
.then(arrayOfObjects => {
var arr1 = arrayOfObjects[0].results;
var arr2 = arrayOfObjects[1].results;
export var movieData = arr1.concat(arr2);
}
)
You can try with a function. like this:
import { API_URL, API_KEY } from '../Config/config';
export const getMovies = () => {
const urls = [
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`,
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=2`,
]
const promises = urls.map(url => {
return new Promise((reject, resolve) => {
fetch(url).then(res => res.json())
.then(res => resolve(res.results))
})
})
return Promise.all(promises)
}
// other file
import {getMovies} from 'YOUR_API_FILE.js';
getMovies().then(moviesArr => {
// your business logics here
})
It's not clear where this code is in relation to your state/reducer, but ideally you should be using action creators to deal with any API calls and dispatch state updates, and those action creators can be called from the component.
So, initialise your state with an empty array:
const initialState = {
movies: []
};
Set up your reducer to update the state with MOVIES_UPDATE:
function reducer(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case 'MOVIES_UPDATE': {
return { ...state, movies: payload };
}
}
}
You can still use your function for fetching data:
function fetchData() {
return Promise.all(urls.map(items => {
return fetch(items).then(response => response.json());
}));
}
..but it's called with an action creator (it returns a function with dispatch param), and this action creator 1) gets the data, 2) merges the data, 3) and dispatches the data to the store.
export function getMovies() {
return (dispatch) => {
fetchData().then(data => {
const movieData = data.flatMap(({ results }) => results);
dispatch({ type: 'MOVIES_UPDATE', payload: movieData });
});
}
}
And it's called from within your component like so:
componentDidMount () {
this.props.dispatch(getMovies());
}
You can modify the code as below:
import { API_URL, API_KEY } from '../Config/config';
let movieData='';
exports.movieData = await (async function(){
const urls = [
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`,
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=2`,
];
const arrayOfObjects = await Promise.all(urls.map(items => {
return fetch(items).then(response => response.json())
}));
return arrayOfObjects[0].results.concat(arrayOfObjects[1].results);
})();

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)

how to write test cases for redux async actions using axios?

Following is a sample async action creator.
export const GET_ANALYSIS = 'GET_ANALYSIS';
export function getAllAnalysis(user){
let url = APIEndpoints["getAnalysis"];
const request = axios.get(url);
return {
type:GET_ANALYSIS,
payload: request
}
}
Now following is the test case I have wrote:
describe('All actions', function description() {
it('should return an action to get All Analysis', (done) => {
const id = "costnomics";
const expectedAction = {
type: actions.GET_ANALYSIS
};
expect(actions.getAllAnalysis(id).type).to.eventually.equal(expectedAction.type).done();
});
})
I am getting the following error:
All actions should return an action to get All Analysis:
TypeError: 'GET_ANALYSIS' is not a thenable.
at assertIsAboutPromise (node_modules/chai-as-promised/lib/chai-as-promised.js:29:19)
at .<anonymous> (node_modules/chai-as-promised/lib/chai-as-promised.js:47:13)
at addProperty (node_modules/chai/lib/chai/utils/addProperty.js:43:29)
at Context.<anonymous> (test/actions/index.js:50:5)
Why is this error coming and how can it be solved?
I suggest you to take a look at moxios. It is axios testing library written by axios creator.
For asynchronous testing you can use mocha async callbacks.
As you are doing async actions, you need to use some async helper for Redux. redux-thunk is most common Redux middleware for it (https://github.com/gaearon/redux-thunk). So assuming you'll change your action to use dispatch clojure:
const getAllAnalysis => (user) => dispatch => {
let url = APIEndpoints["getAnalysis"];
const request = axios.get(url)
.then(response => disptach({
type:GET_ANALYSIS,
payload: response.data
}));
}
Sample test can look like this:
describe('All actions', function description() {
beforeEach("fake server", () => moxios.install());
afterEach("fake server", () => moxios.uninstall());
it("should return an action to get All Analysis", (done) => {
// GIVEN
const disptach = sinon.spy();
const id = "costnomics";
const expectedAction = { type: actions.GET_ANALYSIS };
const expectedUrl = APIEndpoints["getAnalysis"];
moxios.stubRequest(expectedUrl, { status: 200, response: "dummyResponse" });
// WHEN
actions.getAllAnalysis(dispatch)(id);
// THEN
moxios.wait(() => {
sinon.assert.calledWith(dispatch, {
type:GET_ANALYSIS,
payload: "dummyResponse"
});
done();
});
});
});
I found out it was because, I had to use a mock store for the testing along with "thunk" and "redux-promises"
Here is the code which made it solve.
const {expect} = require('chai');
const actions = require('../../src/actions/index')
import ReduxPromise from 'redux-promise'
import thunk from 'redux-thunk'
const middlewares = [thunk,ReduxPromise]
import configureStore from 'redux-mock-store'
const mockStore = configureStore(middlewares)
describe('store middleware',function description(){
it('should execute fetch data', () => {
const store = mockStore({})
// Return the promise
return store.dispatch(actions.getAllDashboard('costnomics'))
.then(() => {
const actionss = store.getActions()
console.log('actionssssssssssssssss',JSON.stringify(actionss))
// expect(actionss[0]).toEqual(success())
})
})
})

Categories

Resources