skip to Main Content

Im making a User Management System where I need to filter the user from a json file, which I have locally. The problem is I can’t fetch the json file and I get this error in console:
Error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The json is located in src/data/data.json
Userlist.jsx is located in src/components/UserList
store.js is located in src/store/store/your textjs

This is the UserList.jsx,where the json is fetched but the data isn’t showing on the Page:

import React, { useEffect , useState} from 'react'
import { useDispatch,useSelector } from 'react-redux'
import { setUsers } from '../store/store'
import UserCard from './UserCard'
import Pagination from './Pagination'



const UserList = () => {

    const dispatch = useDispatch();
    const users = useSelector((state) => state.users.users)
    const [currentPage, setCurrentPage] = useState(1);
    const usersPerPage = 20;
    

    useEffect(() => {
        fetch('../data/heliverse_mock_data.json')
            .then((res) => res.json())
            .then((jsonData) => {
                dispatch(setUsers(jsonData))
            })
            .catch((err) => {
                console.error('Error', err)
            })
    }, [dispatch])





    const handlePageChange = (pageNumber)=>{
        setCurrentPage(pageNumber)
    }

    const indexOfLastUser = currentPage * usersPerPage
    const indexOfFirstUser = indexOfLastUser - usersPerPage
    const currentUsers = users.slice(indexOfFirstUser, indexOfLastUser)
    const totalPages = Math.ceil(users.length / usersPerPage)
    

    return (
        <div className=' grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-8'>

            {currentUsers.map((user) => (
                <UserCard key={user.id} user={user} />
            ))}
            <Pagination totalPages={totalPages} onPageChange={handlePageChange}/>
        </div>
    )

}


export default UserList


This is store.js of redux-toolkit:

import { configureStore, createSlice } from '@reduxjs/toolkit';


const initialState = {
    users: [],
    searchQuery: '',
    domainFilter: '',
    genderFilter: '',
    availabilityFilter: '',
    paginationPage: 1,
    teamMembers: [],
    totalPages: 0
};

const userSlice = createSlice({
    name: 'users',
    initialState,
    reducers: {
        setUsers: (state, action) => {
            state.users = action.payload;
        },
        setSearchQuery: (state, action) => {
            state.searchQuery = action.payload
        },
        setDomainFilter: (state, action) => {
            state.domainFilter = action.payload
        },
        setGenderFilter: (state, action) => {
            state.genderFilter = action.payload;
        },
        setAvailabilityFilter: (state, action) => {
            state.availabilityFilter = action.payload
        },
        setPaginationPage: (state, action) => {
            state.paginationPage = action.payload
        },
        addToTeam: (state, action) => {
            state.teamMembers.push(action.payload)
        },
        removeFromTeam: (state, action) => {
            state.teamMembers = state.teamMembers.filter(
                (user) => user.id !== action.payload
            )
        }
    }
})



const store = configureStore({
    reducer: {
        users: userSlice.reducer
    },
});

export const { setUsers, setSearchQuery, setDomainFilter, setGenderFilter, setAvailabilityFilter, setPaginationPage , addToTeam , removeFromTeam} = userSlice.actions

export default store;

I tried validating the json file thinking maybe the json file might be corrupted but this isn’t the case. I might be thinking maybe the file location directory in fetch() is wrong in my code .

2

Answers


  1. From what you’ve mentioned it seems like there might be some issues related to how the browser handles local file paths when using fetch. While fetch specializes in managing HTTP requests rather than accelerating connection speeds when attempting access into local files such as JSON files we should still find ways to resolve these setbacks. And indeed we have!

    To sidestep any complications that arise while working with something like create react app and fetching from local directories (in-exhaustive) try importing the JSON data straight away into the React component as shown below:

    My Code:

    import React, { useEffect , useState} from 'react'
    import { useDispatch, useSelector } from 'react-redux'
    import { setUsers } from '../store/store'
    import UserCard from './UserCard'
    import Pagination from './Pagination'
    import myData from '../data/heliverse_mock_data.json' // Import your JSON data right there
    
    const UserList = () => {
        // ...
        useEffect(() => {
            dispatch(setUsers(myData)) // Use the data straight away
        }, [dispatch])
        // ...
    }
    
    export default UserList
    

    Using Webpacks JSON loader feature, it is possible to import JSON data as a JavaScript object directly into your code. It is important to keep in mind that larger JSON files may impact your applications performance as they will increase the size of your JavaScript bundle created by Webpack.

    Just as a final check, remember that file paths need to be relative to the file where you’re importing them. So if you have a structure like:

    src
        data
            heliverse_mock_data.json
        components
            UserList.jsx
    

    To do so correctly. Make sure that the reference you provide is relative to where the file being imported is located within your application directory structure. Assuming everything else has been done correctly and there are no issues with corruption or formatting errors in your heliverse_mock_data.json file specifically this change should work without any problems. Happy coding!

    Login or Signup to reply.
  2. Could you try logging and / or sharing the JSON? I’m curious as to whether it’s being packaged correctly by the source you are requesting it from. You can censor the data within, but I’m curious as to the structure as it is being received in the front end.

    Also curious as to whether it may be a promise-fulfillment issue. I could be wrong (I typically use axios for fetches in a seperate "services" file) but I believe the "then" segements are possibly returning an unfulfilled promise if still pending?

    .then((res) => res.json())
    .then((jsonData) => {
                    dispatch(setUsers(jsonData))
                })
    

    is doing nothing with res.json (I think). Try

    .then((res)=> {
    data = await res.json;
    setUsers(data);
    }
    

    You may need to refactor the block of code to be an async function to do it this way. Otherwise, you may be able to use state or set variables without await, and strictly .then()’s. ie

    useEffect(() => {
        let jsonData = null;
        fetch('../data/heliverse_mock_data.json')
            .then((res) => jsonData = res.json())
            .catch((err) => {
                console.error('Error', err)
            });
    
            jsonData.then((jsonData) => {
                dispatch(setUsers(jsonData))
            })
            .catch((err) => {
                console.error('Error', err)
            })
    }, [dispatch])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search