I have an issue in my code, for any reason the Webpack is not letting me to import images dynamically:
The used hook "useImage.js":
import React from 'react'
const useImage = (fileName) => {
const [loading, setLoading] = React.useState(true)
const [error, setError] = React.useState(null)
const [image, setImage] = React.useState(null)
React.useEffect(() => {
const fetchImage = async () => {
try {
const response = await import(fileName) // change relative path to suit your needs
setImage(response)
} catch (err) {
setError(err)
} finally {
setLoading(false)
}
}
fetchImage()
}, [fileName])
return {
loading,
error,
image,
}
}
export default useImage;
The current component "Project":
import React from "react";
import "#styles/project.css";
import useImage from "#hooks/useImage"
const Project = ({project}) => {
const {loading, error, image} = useImage("#images/JavaScript Practice/main.png");
return (
<div className="project">
{loading
? <p>Loading</p>
: <img src={image} className="project__img" alt="Image of the product" id="image" />
}
</div>
)
}
export default Project;
The error:
At this point I really do not understand what is wrong, I have tried many things and nothing works, I hope that one of you has an idea of a solution. Thank you very much for your attention.
Related
I'm trying to fetch the particular blog according to the slug but I'm getting a axios error of 404 not found. i would really appreciate if any one can help..
import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
const data = "https://bulkaccounts.com/api/blogs";
function Singleblog() {
const { slug } = useParams();
const [blog, setBlog] = useState({});
const [isloading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [items, setItems] = useState(null);
useEffect(() => {
const fetchBlogBySlug = async () => {
setIsLoading(true);
try {
const res = await axios.get(`http://localhost:3000/blog/${slug}`);
console.log({ res });
if (res?.data?.data) {
setBlog(res.data.data);
} else {
setError("Blog not found.");
}
} catch (error) {
console.log(error);
setError("Blog not found.");
}
setIsLoading(false);
};
fetchBlogBySlug();
}, [slug]);
let showData = "";
showData = (
<>
<div className="blog">
{data &&
data.datas.data.map((item) => {
return (
<>
<div className="flex-container">
<div className="card">hello</div>
</div>
</>
);
})}
</div>
</>
);
return (
<>
{showData}
<Link to="/">Home</Link>
</>
);
}
export default Singleblog;
// Api = https://bulkaccounts.com/api/blogs
i tried that code but it doesn't worked for me. help me figure out my mistake
First, check if http://localhost:3000/blog is a valid back-end server URL.
I think replacing http://localhost:3000/blog with https://bulkaccounts.com/api/blogs will solve the problem.
I developed an application where I get an api (pokeAPI) with pokemons, and basically I have a global array with "myPokemons", so I want to display all my pokemons except the ones in that array, so I created the function "filterMyPokemons" that I filter the pokemons that should be displayed, and then I call this function in useEffect so that it is updated along with the page, putting a dependency array from the API list. The problem is that I now have an infinite loop that hurts the performance of the application.
import * as C from './styles';
import logo from '../../assets/pokelogo.png';
import { useContext, useState } from 'react';
import { useApi } from '../../hooks/useApi';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Pokelist from '../../components/PokeList';
import CatchingPokemonIcon from '#mui/icons-material/CatchingPokemon';
import CatchContext from '../../context/Context';
const Homepage = () => {
const api = useApi();
const { showMyPokemons } = useContext(CatchContext);
const navigate = useNavigate();
const [pokemonList, setPokemonList] = useState([]);
const [loading, setLoading] = useState(false);
const [text, setText] = useState('');
const [myPokemonsList, setMyPokemonsList] = useState([]);
const [pokemonListFiltered, setPokemonListFiltered] = useState([]);
useEffect (() => {
const getAllPokemons = async () => {
const myPokemons = await showMyPokemons();
const pokemon = await api.getAllPokemon();
setLoading(true);
setPokemonList(pokemon);
setMyPokemonsList(myPokemons);
setLoading(false);
}
filterMyPokemons();
getAllPokemons();
}, [myPokemonsList]);
const filterMyPokemons = async () => {
const filteredList = await pokemonList.filter(pokemons => !myPokemonsList.includes(pokemons.name))
return setPokemonListFiltered(filteredList);
};
const lowerSearch = text.toLocaleLowerCase();
const filteredPokemons = pokemonListFiltered.filter(pokemon => pokemon
.name.toLowerCase().includes(lowerSearch)
);
const handleHome = () => {
navigate('/')
}
const handleMyPokemons = () => {
navigate('/mypokemons')
}
return (
<C.Container>
<C.Logo>
<img src={logo} alt="" />
</C.Logo>
<C.Navbar>
<input
type="text"
placeholder='Busque um pokémon...'
onChange={(e) => setText(e.target.value)}
value={text}
/>
</C.Navbar>
<C.Pokedatabase onClick={handleMyPokemons}>
<button>Meus pokémons <i><CatchingPokemonIcon /></i></button>
</C.Pokedatabase>
<C.Pokelist>
{filteredPokemons.map(pokemon => {
return (
<Pokelist
name={pokemon.name}
/>
)
})}
</C.Pokelist>
</C.Container>
)
}
export default Homepage;
If I leave useEffect's dependency array empty, the items are not displayed, but if I leave any dependencies it causes an infinite loop. How to solve this problem?
The problem comes with updating the myPokemonsList array within the useEffect hook that depends on that array.
useEffect (() => {
const getAllPokemons = async () => {
const myPokemons = await showMyPokemons();
const pokemon = await api.getAllPokemon();
setLoading(true);
setPokemonList(pokemon);
setMyPokemonsList(myPokemons); // Here's the infinite loop
setLoading(false);
}
filterMyPokemons();
getAllPokemons();
}, [myPokemonsList]); // Here's the infinite loop
You should have another use effect for updates on the myPokemonList in order to avoid updating and depending on the same list.
Ahoy,
Getting an error with Stripe in Gatsby occurs on page load
Uncaught (in promise) TypeError: maybeStripe.apply is not a function
import React, { useEffect, useState } from 'react';
import { loadStripe } from '#stripe/stripe-js';
import { Elements } from '#stripe/react-stripe-js';
import StripeCheckout from './stripeCheckout'
const stripePromise = loadStripe('pk_test_xyz');
function App() {
const [clientSecret, setClientSecret] = useState('');
useEffect(() => {
fetch("/.netlify/functions/createIntent")
.then((res) => res.json())
.then(({ clientSecret }) => setClientSecret(clientSecret));
}, [])
const options = {
clientSecret,
}
return (
<main>
<h1>Payment</h1>
{clientSecret && (
<Elements stripe={stripePromise} options={options}>
<StripeCheckout />
</Elements>
)}
</main>
);
}
export default App;
import {
PaymentElement
} from '#stripe/react-stripe-js'
import React, {useState} from 'react'
import {useStripe, useElements} from '#stripe/react-stripe-js';
export default function CheckoutForm() {
const stripe = useStripe();
const elements = useElements();
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) {
return;
}
setIsLoading(true);
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: "http://localhost:8888",
},
});
if (error.type === "card_error" || error.type === "validation_error") {
setMessage(error.message);
} else {
setMessage("An unexpected error occured.");
}
setIsLoading(false);
}
return (
<form id="payment-form" onSubmit={handleSubmit}>
<PaymentElement id="payment-element" />
<button disabled={isLoading || !stripe || !elements} id="submit">
<span id="button-text">
{isLoading ? <div className="spinner" id="spinner"></div> : "Pay now"}
</span>
</button>
{message && <div id="payment-message">{message}</div>}
</form>
)
}
Can't seem to find any ref's to this issue on here or stripes documentation, not sure if this is a Gatsby issue or I am just doing something wrong.
Any help is greatly appreciated
cheers
Removed node_modules and reinstalled and added import { loadStripe } from '#stripe/stripe-js/pure';
You may have installed other modules like #stripe/stripe-js but I don't think you installed the main stripe module. So run npm i stripe or yarn add stripe and the error will be fixed
Here is my code the problem is that it is getting the state of imgAddress when it's still nothing => "" and the state is never being changed I'm not getting the new state of imgAddress in the <p></p> tag neither Help me please the problem is the async-ity but I can't solve it
import React, { useState, useEffect } from 'react'
import * as fb from 'firebase';
export default function Page() {
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [age, setAge] = useState(0);
const [img, setImg] = useState("");
const [imgAddress, setImgAddress] = useState("");
useEffect(() => { //useEffect որտև անվերջ անում ա stackoverflow-ում հարցրել էի մի անգամ
fb.database().ref('users/' + fb.auth().currentUser.uid).on('value', (e) => {
let db = e.val();
console.log(db);
setAge(db.age);
setUsername(db.username);
setImg(db.img);
setEmail(db.email);
});
fb.auth().onAuthStateChanged(() => {
if (img != "") {
console.log('mtav user');
fb.storage().ref(`avatars/${fb.auth().currentUser.uid}/${img}`).getDownloadURL().then(e => {
console.log('LALALALALALALALA')
console.log(e);
setImgAddress(e);
})
.catch(e => console.log(e))
}
else {
console.log("chmtav");
}
})
}, []);
return (
<>
<h1>Hello</h1>
<ul>
<li>Email: {email}</li>
<li>Username: {username}</li>
<li>Image name: {img}</li>
<li>Age: {age}</li>
Image
<p>{imgAddress}</p>
</ul>
</>
)
}
<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>
Ok I figured it out finally, I just moved the getting code out from the useEffect and now it works, but I don't understand why if anyone could explain me I would mark is answer as a correct one, btw Now it consoles it 4-5 times randomly
I need to get a list of repositories using GitHub API, search has to work on button click and on change selectBox with licences
import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import moment from "moment";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";
import "./App.css";
export const App = () => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError] = useState(false);
const [nameSearch, setNameSearch] = useState("");
const [license, setLicense] = useState({});
const fetchData = useCallback(async () => {
setHasError(false);
setIsLoading(true);
try {
const prevMonth = moment()
.subtract(30, "days")
.format("YYYY-MM-DD");
const licenseKey = (license && license.key) || "";
const response = await axios(
`https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
licenseKey ? `+license:${licenseKey}` : ""
}&sort=stars&order=desc`
);
setData(response.data.items);
} catch (error) {
setHasError(true);
setData([]);
}
setIsLoading(false);
}, [license]);
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<Layout>
<Header>
<Search
handleSearchChange={setNameSearch}
nameSearch={nameSearch}
isLoading={isLoading}
onSearch={fetchData}
/>
<Licenses license={license} handleLicenseChange={setLicense} />
</Header>
<main>
{hasError && <div>Error</div>}
{isLoading ? <Loader /> : <List data={data} />}
</main>
</Layout>
);
};
First of all, I get warning
Compiled with warnings.
./src/components/App/App.js
Line 42:6: React Hook useCallback has a missing dependency: 'nameSearch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
And my search is not working because nameSearch is always empty in the query string.
How to make search work?
Try adding nameSearch to the list of dependencies for useCallback:
const fetchData = useCallback(async () => {
...
}, [license, nameSearch]);
and make sure setNameSearch is actually used inside Search.js so that it will have a value.