Hello everyone I'm a beginner currently learning programming, I'm trying to make a webapp that fetches posts from reddit and displays them in a website, I have created an async thunk to fetch the data from a reddit API, when I log it to the console the data is displayed, but whenever I try calling the fetch function and save it to a const instead of returning the object as it normally does, it returns the function.
reddit.js API fetch function
export const API_URL = 'https://www.reddit.com';
export const fetchNewPosts = () => async () => {
const response = await fetch(`${API_URL}/new.json`);
const json = await response.json();
console.log(json.data.children.map((post) => post.data))
const posts = json.data.children.map((post) => post.data)
return posts
}
Feed.jsx 'fetchNewPosts()' renders an object w/ 25 posts when dispatched in Feed.jsx
import React from 'react';
import {Stats} from '../components/Stats';
import { Post } from '../components/Post/Post'
import { useDispatch, useSelector } from 'react-redux';
import './Feed.css'
import { useEffect } from 'react';
import { getPosts } from '../api/postsSlice';
import { fetchNewPosts } from '../api/reddit';
export const Feed = () => {
const allInfo = useSelector(state => state.postsReducer);
const { posts, isLoading, error } = allInfo;
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPosts());
dispatch(fetchNewPosts())
}, [dispatch])
...
postsSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { fetchNewPosts } from "./reddit";
export const postsSlice = createSlice({
name: 'postsSlice',
initialState: {
posts: [],
isLoading: false,
error: false,
errorMessage: '',
searchTerm: '',
},
reducers: {
startGetPosts (state) {
state.isLoading = true;
},
getPostsSuccess (state, action) {
state.isLoading = false;
state.posts = action.payload;
},
getPostsFailed (state, action) {
state.isLoading = false;
state.error = true;
state.errorMessage = action.payload;
}
}
})
export const getPosts = () => async (dispatch) => {
try {
dispatch(startGetPosts());
const posts = await fetchNewPosts();
console.log(posts)
dispatch(getPostsSuccess());
} catch (error) {
dispatch(getPostsFailed(error.message))
}
}
export const selectPosts = (state) => state.postsSlice.posts;
export const {
startGetPosts,
getPostsSuccess,
getPostsFailed
} = postsSlice.actions;
export default postsSlice.reducer;
I appreciate any feedback I can get.