Failed to compile: Module not found: Can't resolve in ReactJS - javascript

I was about rounding up this activity and I started getting this error:
Module not found: Can't resolve './components/Post' in ./src/pages/index.js
I have tried all I could but was not able to solve this problem. Below is the list of my codes:
index.js
import React, { useState, useEffect } from 'react';
import Posts from './components/Pagination';
import Pagination from './components/Post';
import axios from 'axios';
const Home = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
setPosts(res.data);
setLoading(false);
};
fetchPosts();
}, []);
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div
style={{
display: 'flex',
height: '90vh'
}}
>
<img src={require('../images/top_img.jpg')} alt='logo' height='500px' width='100%'/>
<div className='container mt-5'>
<h1 className='text-primary mb-3'>LATEST NEWS</h1>
<Posts posts={currentPosts} loading={loading} />
<Pagination
postsPerPage={postsPerPage}
totalPosts={posts.length}
paginate={paginate}
/>
</div>
</div>
);
};
export default Home;
Post.js
import React from 'react';
const Posts = ({ posts, loading }) => {
if (loading) {
return <h2>Loading...</h2>;
}
return (
<ul className='list-group mb-4'>
{posts.map(post => (
<li key={post.id} className='list-group-item'>
{post.title}
</li>
))}
</ul>
);
};
export default Posts;
Pagination.js
import React from 'react';
const Posts = ({ posts, loading }) => {
if (loading) {
return <h2>Loading...</h2>;
}
return (
<ul className='list-group mb-4'>
{posts.map(post => (
<li key={post.id} className='list-group-item'>
{post.title}
</li>
))}
</ul>
);
};
export default Posts;
Below is the structure of my code:

I believe your object names are swapped.

Isn't there an error of relative path?
import Posts from '../components/Pagination';
import Pagination from './components/Post';
both imports are in the same file and both files are in the same folder, but one has ../ and other ./

First, you I would make the named imports match the file structure:
import Post from "./components/Post"
import Pagination from "./components/Pagination"
Also, your default exports are messing things up as well. You will want to export Pagination and then in ./Post you want to export Post.
Lastly, your paths were messed up. The "components" folder is on the same level as index.js. Thus, you can access it through "./components"

Related

React infinite scroll in an Unsplash image app

I am building an image search app using Unsplash API and trying to implement react infinite scroll (https://www.npmjs.com/package/react-infinite-scroll-component), but it is not working properly.
Now, the search form works fine and it displays 10 images(which is the default number of images using Unsplash API) when you search something, but when I scroll down to the end of of the page, it only displays the loader (h4 'Loading') but it does not display more images.
App.js
import './App.css';
import Main from './components/Main';
function App() {
return (
<div className="App">
<Main />
</div>
);
}
export default App;
Main.js
import React from 'react'
import Header from './Header'
import Image from './Image'
import { useState, useEffect } from 'react'
import InfiniteScroll from 'react-infinite-scroll-component';
function Main() {
const [input, setInput] = useState('')
const [allImages, setAllImages] = useState([])
const [favorites, setFavorites] = useState(() => JSON.parse(localStorage.getItem("favorites")) || [])
useEffect(() => {
localStorage.setItem("favorites", JSON.stringify(favorites))
console.log(favorites)
}, [favorites])
function handleChange(event) {
setInput(event.target.value)
}
async function fetchImages() {
try {
const res = await fetch(`https://api.unsplash.com/search/photos?&query=${input}&client_id=${process.env.REACT_APP_UNSPLASH_API_KEY}`)
const data = await res.json();
setAllImages(data.results)
} catch(error) {
alert("Sum ting wong");
}
}
const handleSubmit = async (event) => {
event.preventDefault();
fetchImages()
}
console.log(`allImages: ${allImages.length}`);
// use parameter 'id' to read specific one
function isLiked(id) {
return favorites.find(el => el.id === id) ? true : false
}
return (
<main>
<Header
input={input}
handleChange={handleChange}
handleSubmit={handleSubmit}
/>
<InfiniteScroll
dataLength={allImages.length} //This is important field to render the next data
next={fetchImages}
hasMore={true}
loader={<h4>Loading...</h4>}
>
<div className='main--image-list mt-5 pb-5'>
{allImages.map(el => (
<Image
key={el.id}
// do need spread operator below for img's src to work in Image.js
{...el}
el={el}
isLiked={isLiked(el.id)}
favorites={favorites}
setFavorites={setFavorites}
/>
))}
</div>
</InfiniteScroll>
</main>
)
}
export default Main
for visuals

React.js flickering issue

I followed the online course to make a website and I realized that my website is blinking when I move to other pages. Are there any problems in my codes?
parent
import "./Product.css";
import Product from "./Product";
import { useLayoutEffect, useState } from "react";
import axios from "axios";
export default function Body() {
const [products, SetProducts] = useState([]);
useLayoutEffect(() => {
async function fetchProducts() {
const { data } = await axios.get("http://127.0.0.1:8000/api/products/");
SetProducts(data);
}
fetchProducts();
}, []);
return (
<div className="product">
{products.map((data) => (
<div key={data.id} className="product_child">
<Product product={data} />
</div>
))}
</div>
);
}
child
import { Link } from "react-router-dom";
export default function Product({ product }) {
return (
<div className="product">
<div className="prodcut_child">
<Link
style={{ color: "inherit", textDecoration: "none" }}
to={`/product/${product.id}`}
>
<img src={product.img} alt="img" />
<p>{product.title}</p>
<h1 style={{ fontSize: "1.3rem" }}>${product.price}</h1>
</Link>
</div>
</div>
);
}
I used useEffect and it was blinking, so I tried useLayoutEffect instead but still, it happens.. (I used Link tag tho)
Is it because I use async await to fetch api data?
Or I am using django rest_framework, is it a problem with low speed of django rest_framework??
thank you..!
I think its because of the async await request that your doing.
You should try and implement the loading feature in your app
something like this
export default function Body() {
const [products, SetProducts] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
async function fetchProducts() {
setLoading(true);
const { data } = await axios.get("http://127.0.0.1:8000/api/products/");
SetProducts(data);
}
fetchProducts();
setLoading(false);
}, []);
if (loading) return <div>loading...</div>
...
}

undefined is not an object axios

I'm getting this error when i try to use GET method in AXIOS. At the bottom I put a code snippet without style. Wants to grab data from the API using AXIOS. I'm new and don't quite know how to do this correctly.
undefined is not an object (evaluating 'data.map')
code:
import React, {useState, useEffect} from 'react';
import axios from 'axios';
const HomeScreen = ({navigation}) => {
const [categoryIndex, setCategoryIndex, data, setData] = useState([])
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
};
fetchData();
}, []);
return (
<SafeAreaView
<ul>
{data.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
</SafeAreaView>
);
};
export default HomeScreen;
Hi, your data is not like you expected. There is also "hits" variable that exists, I think you want to show that data.
In the first render, it's trying to map your data but data was not filled when trying to map it.
Also, you should be re-examined "useState" usage.
And you need to check if data exist before the map it (data?.hits).
And you forgot to close the SafeAreaViewtag.
https://reactjs.org/docs/hooks-state.html
https://codesandbox.io/s/ancient-fast-pdqhy?file=/src/TestApp.jsx
If you paste this it will work correctly:
import React, { useState, useEffect } from "react";
import axios from "axios";
const HomeScreen = ({ navigation }) => {
const [data, setData] = useState([]);
const [categoryIndex, setCategoryIndex] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
"https://hn.algolia.com/api/v1/search?query=redux"
);
console.log(result);
setData(result.data);
};
fetchData();
}, []);
return (
<SafeAreaView>
<ul>
{data?.hits &&
data.hits.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
</SafeAreaView>
);
};
export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Custom pagination using ReactJS

I have this project for pagination of json data received through an API. The problem is that my code somehow gives me a 'slice' error (it is not the case when using other API's, e.g. https://corona.lmao.ninja/v2/countries) <--- Works fine
Items.js:
import React from 'react';
import { ITEMS_PER_PAGE } from '../utils/constants';
import Data from './Data';
const Items = ({ items, page }) => {
const startIndex = (page - 1) * ITEMS_PER_PAGE;
const selectedItems = items.slice(startIndex, startIndex + ITEMS_PER_PAGE);
return (
<React.Fragment>
{selectedItems.map(item => (
<Data key={item.country} {...item} />
))}
</React.Fragment>
);
};
export default Items;
Data.js:
import React from 'react';
const Data = ({ Data }) => {
const { high, low } = Data;
return (
<div class="data">
<p>
<strong>Test:</strong> {high} {low}
</p>
<hr />
</div>
);
};
export default Data;
Pagination.js:
import React from 'react';
const Pagination = ({ totalPages, handleClick, page }) => {
const pages = [...Array(totalPages).keys()].map(number => number + 1);
return (
<div className="numbers">
{pages.map(number => (
<a
key={number}
href="/#"
onClick={() => handleClick(number)}
className={`${page === number && 'active'}`}
>
{number}
</a>
))}
</div>
);
};
export default Pagination;
App.js:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Pagination from './components/Pagination';
import Items from './components/Items';
import { ITEMS_PER_PAGE } from './utils/constants';
const App = () => {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
axios
.get('https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=10')
.then(response => {
const result = response.data;
setItems(result);
setTotalPages(Math.ceil(result.length / ITEMS_PER_PAGE));
setIsLoading(false);
});
}, []);
const handleClick = number => {
setPage(number);
};
return (
<div>
<h1>Pagination Demo</h1>
{isLoading ? (
<div className="loading">Loading...</div>
) : (
<React.Fragment>
<Items items={items} page={page} />
<Pagination
totalPages={totalPages}
handleClick={handleClick}
page={page}
/>
</React.Fragment>
)}
</div>
);
};
export default App;
My problem seems to be something that am I missing with this other API: https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=10
error: TypeError: items.slice is not a function in Items.js
Any help would be appreciated!
The response from the API has 2 nested Data keys, so it has to be like this:
const result = response.data;
setItems(result.Data.Data);
Data.js
import React from 'react';
const Data = ({ high, low }) => {
return (
<div class="data">
<p>
<strong>Test:</strong> {high} {low}
</p>
<hr />
</div>
);
};
export default Data;
demo: https://stackblitz.com/edit/react-arqaxj

React, Adding data from json to single post component

I try to write website in React and that was going fine until now. I totally got stuck.
I have component with list of posts which is working fine. My problem is, that I dont know how to add data from JSON to single post component. I was trying to change geting my JSON data from list articles component to app.js and then passing it down to component with my list posts and to single post component, but then I have error with map() function.
//geting data from JSON and passing it through props down
import React, { useEffect, useState } from "react";
import "./style.css";
import SideBar from "../SideBar";
import MainContent from "../MainContent";
import blogData from "../../assets/data/blog.json";
const MainContainer = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const post = blogData.data;
setPosts(post);
}, []);
return (
<div className="main-container">
<MainContent posts={posts} />
<SideBar posts={posts} />
</div>
);
};
export default MainContainer;
//mapping through posts
import React from "react";
import "./style.css";
import Post from "../Post";
const MainContent = ({ posts }) => {
return (
<main className="main-content">
{posts.map(post => {
return <Post key={post.id} post={post} />;
})}
</main>
);
};
export default MainContent;
//Post from list of posts
const Post = ({ post }) => {
return (
<div className="post">
<Animated
animationIn="bounceInLeft"
animationOut="fadeOut"
isVisible={true}
>
<h3 className="postTitle">{post.blogTitle}</h3>
<div className="imgContainer">
<img
alt="travel"
src={require("../../assets/img/" + post.blogImage)}
></img>
</div>
<p className="postDescription">{post.blogText}</p>
<NavLink to={`/post/${post.id}`}>
<h5 className="postLink">Read more</h5>
</NavLink>
<h5 className="posteDate">
Posted on {post.postedOn} by {post.author}
</h5>
</Animated>
</div>
);
};
export default Post;
Here is link to my repo:
https://github.com/Gitarrra92/travel-blog/
I think I should have a state in my component with single object of specific id. I just still dont know how to do this. This is my SinglePost component
const SinglePost = ({ match }) => {
const [singlePosts, setSinglePost] = useState({});
useEffect(() => {
const singlePost = blogSingleData.data;
setSinglePost(singlePost);
console.log(singlePost);
}, [match]);
return (
<>
<Socials />
</>
);
};
export default SinglePost;

Categories