Iam trying to pass the number of the page in (fetchPlanets) function
put it's gets the following error
here is the code
import React, { useState } from 'react'
import { useQuery } from 'react-query'
import Planet from './Planet'
const fetchPlanets = async (key, page) => {
const res = await fetch(`http://swapi.dev/api/planets/?page=${page}`)
return res.json()
}
const Planets = () => {
const [page, setPage] = useState(1)
const { data, status } = useQuery(['planets', page], fetchPlanets)
return (
<div>
<h2>Planets</h2>
<button onClick={() => setPage(1)}>Page 1</button>
<button onClick={() => setPage(2)}>Page 2</button>
<button onClick={() => setPage(3)}>Page 3</button>
{status === 'loading' && (
<div>Loading Data</div>
)}
{status === 'error' && (
<div>Error Fetching Data</div>
)}
{status === 'success' && (
<div>
{data.results.map(planet => <Planet planet={planet} key={planet.name} />)}
</div>
)}
</div>
)
}
export default Planets
as you can see the variable page in async function is giving value undefined
When using queryKeys, you need to destructure the property from the fetcher function arguments:
const fetcher = ({ queryKey )) => {...};
or
const fetcher = props => {
const { queryKey } = props;
...etc
}
Then you can use the keys based upon their position:
// queryKeys: ["planets", 1]
const [category, page] = queryKeys;
const res = await fetch(`https://swapi.dev/api/${category}/?page=${page}`);
Working example:
Planets.js
import React, { useState } from "react";
import { useQuery } from "react-query";
// import Planet from "./Planet";
const fetchPlanets = async ({ queryKey }) => {
const [category, page] = queryKey;
const res = await fetch(`https://swapi.dev/api/${category}/?page=${page}`);
return res.json();
};
const Planets = () => {
const [page, setPage] = useState(1);
const { data, status } = useQuery(["planets", page], fetchPlanets);
return (
<div className="app">
<h2>Planets</h2>
<button onClick={() => setPage(1)}>Page 1</button>
<button onClick={() => setPage(2)}>Page 2</button>
<button onClick={() => setPage(3)}>Page 3</button>
{status === "loading" && <div>Loading Data</div>}
{status === "error" && <div>Error Fetching Data</div>}
{status === "success" && (
<pre className="code">{JSON.stringify(data.results, null, 4)}</pre>
)}
</div>
);
};
export default Planets;
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import Planets from "./Planets";
import "./styles.css";
const queryClient = new QueryClient();
ReactDOM.render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<Planets />
</QueryClientProvider>
</StrictMode>,
document.getElementById("root")
);
Related
This is my code:
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { useLocation } from 'react-router-dom'
import Button from 'react-bootstrap/esm/Button'
const BookingScreen = () => {
const [room, setRoom] = useState([])
const [loading, setLoading] = useState()
const location = useLocation()
const path = location.pathname.split("/",5)[4]
useEffect(() => {
fetchData()
},[])
const fetchData = async () => {
const res = await axios.get("http://localhost:5000/api/room/" + path)
setRoom(res.data)
console.log(res.data)
setLoading(false)
}
const singleRoom = room.map((item) => {
return (
<div key={item._id} >
<div className="row justify-content-md-center mt-4 ">
<div className="col-md-6">
<img src={item.imageUrl
[0]
} alt="singleRoom" />
</div>
<div className="col-md-4">
<h2>{item.name}</h2>
<p>{item.desc}</p>
<p>Category : {item.categoy}</p>
<Button variant="secondary">
Book Now </Button>
</div>
</div>
</div>
)
})
return (
<>
{loading ? <h1>Loading ...</h1> : singleRoom}
</>
)
}
export default BookingScreen
I'm trying to populate the list singleRoom but it keeps saying map is not a function when I console data I'm getting everything and after that, I used setRoom hook to set the data, but somehow it's empty.
Things i would say, is that if the data returns as an array then its fine, otherwise you'll need to change your logic of return.
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { useLocation } from 'react-router-dom'
import Button from 'react-bootstrap/esm/Button'
const BookingScreen = () => {
const [room, setRoom] = useState([])
const [loading, setLoading] = useState(true) // set to true by default
const location = useLocation()
useEffect(() => {
fetchData()
}, [])
const fetchData = async () => {
const path = location.pathname.split("/", 5)[4]
setLoading(true)
try {
const res = await axios.get(`http://localhost:5000/api/room/${path}`)
if (res.data) {
setRoom(res.data); // does this actually return an array?
setLoading(false)
} else {
setRoom([]) // force back an empty array if data wasn't returned
setLoading(false)
}
} catch (err) {
setRoom([]) // set back to empty
setLoading(false)
// I'd usually also do an error state here.
}
}
const singleRoom = room.length > 0 ? room.map(({ _id, imageUrl, name, desc, categoy }) => (
<div key={_id} >
<div className="row justify-content-md-center mt-4 ">
<div className="col-md-6">
<img src={imageUrl
[0]
} alt="singleRoom" />
</div>
<div className="col-md-4">
<h2>{name}</h2>
<p>{desc}</p>
<p>Category : {categoy}</p>
<Button variant="secondary">
Book Now </Button>
</div>
</div>
</div>
)
) : <div>No room data found</div>
return (
<>
{loading ? <h1>Loading ...</h1> : singleRoom}
</>
)
}
export default BookingScreen
I am trying to get the id from a doc when I click a delete button. so the user can delete the post.
I got far enough to show the button if the user is the uploader.
but, I don't know how to get the id from the clicked document.
I tried this:
{auth.currentUser.uid === uploaderId ? (
<div
onClick={(e) => {
if (auth.currentUser.uid === uploaderId) {
e.stopPropagation();
deleteDoc(doc(db, "posts", id));
}
}}
>
<div>
<button>🗑️</button>
</div>
</div>
) : (
<div>
</div>
)}
but that doesn't work and gives me the error:
Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf')
so to summarize how do I get the id from the document
full code:
import React, { useEffect, useRef, useState } from 'react';
import './App.css';
import { initializeApp } from "firebase/app";
import { getFirestore, collection, orderBy,
query, Timestamp, addDoc, limitToLast,
deleteDoc, doc, } from "firebase/firestore";
import { confirmPasswordReset, getAuth, GoogleAuthProvider, signInWithPopup, } from "firebase/auth";
import { useAuthState } from "react-firebase-hooks/auth";
import { useCollectionData } from "react-firebase-hooks/firestore";
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
function App() {
const [user] = useAuthState(auth);
return (
<div className="App">
<Header/>
{/* <Picker/> */}
<section>
<SignOut/>
{/* <ShowProfile/> */}
<Upload/>
{user ? <Feed /> : <SignIn />}
</section>
</div>
);
}
function Header() {
return (
<h1 className='headerTxt'>SHED</h1>
)
}
// function Picker() {
// }
function SignIn() {
const signInWithGoogle = () =>{
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
}
return (
<button className='SignIn' onClick={signInWithGoogle}>sign in with google</button>
)
}
function SignOut() {
return auth.currentUser && (
<button onClick={() => auth.signOut()}>Sign out</button>
)
}
function Feed() {
const postsRef = collection(db, 'posts');
const qwery = query(postsRef,orderBy('createdAt'), limitToLast(25), );
const [posts] = useCollectionData(qwery, {idField: "id"});
return (
<>
<main>
{posts && posts.map(msg => <Post key={msg.id} post={msg} />)}
</main>
</>
)
}
function Post(props) {
const {text, photoURL, displayName, uid, uploaderId, id} = props.post;
return (
<div className={"post"}>
<div className='msg'>
<div className='top'>
<img src={photoURL} alt="" />
<sub>{displayName}</sub>
</div>
<hr />
<p>{text}</p>
{auth.currentUser.uid === uploaderId ? (
<div
onClick={(e) => {
if (auth.currentUser.uid === uploaderId) {
e.stopPropagation();
deleteDoc(doc(db, "posts", id));
}
}}
>
<div>
<button>🗑️</button>
</div>
</div>
) : (
<div>
</div>
)}
{/* <button>❤️</button> */}
</div>
</div>
)
}
// function ShowProfile() {
// return(
// <div>
// <button onClick={queryMine}>my posts</button>
// </div>
// )
// }
function Upload() {
const postsRef = collection(db, 'posts');
const [formValue, setFormValue] = useState('');
const sendpost = async(e) =>{
e.preventDefault();
const {uid, photoURL, displayName} = auth.currentUser;
if (formValue !== "" && formValue !== " ") {
await addDoc(postsRef, {
text: formValue,
createdAt: Timestamp.now(),
displayName,
uploaderId: uid,
photoURL
})
setFormValue('')
}
}
return auth.currentUser &&(
<form onSubmit={sendpost}>
<textarea name="" id="" cols="30" rows="10"
value={formValue} onChange={(e) => setFormValue(e.target.value)}
></textarea>
<button type='submit'>➜</button>
</form>
)
}
export default App;```
Get the data (doc id and doc data) using querySnapshot and merge them into one object. Save an array of objects to a state and pass what you need as properties. For example:
...
const querySnapshot = await getDocs(collection(db, `users/${email}/todos`))
const todos = []
querySnapshot.forEach(doc => {
todos.push({
id: doc.id,
text: doc.data().text,
isCompleted: doc.data().isCompleted,
})
})
return todos
Here is a simple example of the Todo App, but the logic is the same. In the Todo component, I get the doc id as props. Full code:
import { collection, getDocs } from 'firebase/firestore'
import { useEffect, useState } from 'react'
import { db } from '../../app/firebase'
import Todo from '../Todo'
import './style.css'
const TodoList = () => {
const [todos, setTodos] = useState()
useEffect(() => {
const getData = async () => {
const querySnapshot = await getDocs(collection(db, 'users/kvv.prof#gmail.com/todos'))
const todos = []
querySnapshot.forEach(doc => {
todos.push({
id: doc.id,
text: doc.data().text,
isCompleted: doc.data().isCompleted,
})
})
return setTodos(todos)
}
getData()
}, [])
return (
<section className="todo-list">
{todos?.map(todo => (
<Todo key={todo.id} id={todo.id} text={todo.text} isCompleted={todo.isCompleted} />
))}
</section>
)
}
export default TodoList
If you use react-firebase-hooks, then you need to use this
I try to change the icon and add it to favorites when I click on it. It works fine, my icon is changed but it impacts all my images icons instead of one. How can I fix this? Here is my code:
import React, { useState, useEffect } from "react";
import AddCircleOutlineIcon from '#mui/icons-material/AddCircleOutline';
import CheckCircleOutlineIcon from '#mui/icons-material/CheckCircleOutline';
import ExpandCircleDownIcon from '#mui/icons-material/ExpandCircleDown';
import PlayCircleIcon from '#mui/icons-material/PlayCircle';
const Row = () => {
const [image, setImage] = useState([])
const [favorite, setFavorite] = useState(false);
useEffect(() => {
...
}, []);
const addToFavorite = () => {
...
}
return (
<div >
{image.map((item) => {
return (
<div key={item.id}>
<span>{item.title}</span>
<span>{item.description}</span>
<img src={...} alt={image.title}/>
<div onClick={() => setFavorite(!favorite)}>
{favorite ? < CheckCircleOutlineIcon onClick={() => addToFavorite()} /> : < AddCircleOutlineIcon onClick={() => addToFavorite()} />}
</div>
)
})}
</div>
);
}
export default Row;
Your problem is favorite state is only true/false value, when it's true, all images will have the same favorite value.
The potential fix can be that you should check favorite based on item.id instead of true/false value
Note that I added updateFavorite function for handling favorite state changes on your onClick
Here is the implementation for multiple favorite items
import React, { useState, useEffect } from "react";
import AddCircleOutlineIcon from '#mui/icons-material/AddCircleOutline';
import CheckCircleOutlineIcon from '#mui/icons-material/CheckCircleOutline';
import ExpandCircleDownIcon from '#mui/icons-material/ExpandCircleDown';
import PlayCircleIcon from '#mui/icons-material/PlayCircle';
const Row = () => {
const [image, setImage] = useState([])
const [favorite, setFavorite] = useState([]);
useEffect(() => {
...
}, []);
const updateFavorite = (itemId) => {
let updatedFavorite = [...favorite]
if(!updatedFavorite.includes(itemId)) {
updatedFavorite = [...favorite, itemId]
} else {
updatedFavorite = updatedFavorite.filter(favoriteItem => itemId !== favoriteItem)
}
setFavorite(updatedFavorite)
}
const addToFavorite = () => {
...
}
return (
<div >
{image.map((item) => {
return (
<div key={item.id}>
<span>{item.title}</span>
<span>{item.description}</span>
<img src={...} alt={image.title}/>
<div onClick={() => updateFavorite(item.id)}>
{favorite.includes(item.id) ? < CheckCircleOutlineIcon onClick={() => addToFavorite()} /> : < AddCircleOutlineIcon onClick={() => addToFavorite()} />}
</div>
)
})}
</div>
);
}
export default Row;
Here is the implementation for a single favorite item
import React, { useState, useEffect } from "react";
import AddCircleOutlineIcon from '#mui/icons-material/AddCircleOutline';
import CheckCircleOutlineIcon from '#mui/icons-material/CheckCircleOutline';
import ExpandCircleDownIcon from '#mui/icons-material/ExpandCircleDown';
import PlayCircleIcon from '#mui/icons-material/PlayCircle';
const Row = () => {
const [image, setImage] = useState([])
const [favorite, setFavorite] = useState(); //the default value is no favorite item initially
useEffect(() => {
...
}, []);
const updateFavorite = (itemId) => {
let updatedFavorite = favorite
if(itemId !== updatedFavorite) {
updatedFavorite = itemId
} else {
updatedFavorite = null
}
setFavorite(updatedFavorite)
}
const addToFavorite = () => {
...
}
return (
<div >
{image.map((item) => {
return (
<div key={item.id}>
<span>{item.title}</span>
<span>{item.description}</span>
<img src={...} alt={image.title}/>
<div onClick={() => updateFavorite(item.id)}>
{favorite === item.id ? < CheckCircleOutlineIcon onClick={() => addToFavorite()} /> : < AddCircleOutlineIcon onClick={() => addToFavorite()} />}
</div>
)
})}
</div>
);
}
export default Row;
This is what you're looking for based on the code you've provided:
import { useState, useEffect } from "react";
const Item = ({ item }) => {
const [favorite, setFavorite] = useState(false);
const toggleFavorite = () => setFavorite((favorite) => !favorite);
return (
<div>
<span>{item.title}</span>
<span>{item.description}</span>
<span onClick={toggleFavorite>
{favorite ? "[♥]" : "[♡]"}
</span>
</div>
);
};
const Row = () => {
const [items, setItems] = useState([]);
useEffect(() => {
// use setItems on mount
}, []);
return (
<div>
{items.map((item) => <Item item={item} key={item.id} />)}
</div>
);
};
export default Row;
You can break up your code into smaller components that have their own states and that's what I did with the logic that concerns a single item. I've created a new component that has its own state (favorited or not).
I am creating a blog website in which I am embedding react-draft-wysiwyg editor. I am facing problem when the user has to update the blog. When I click the update button the content is gone. I looked into many solutions but I couldn't make it work.
This is my code
import axios from "axios";
import React, { useContext, useEffect, useState } from "react";
import { useLocation } from "react-router";
import { Link } from "react-router-dom";
import { Context } from "../../context/Context";
import "./singlePost.css";
import { EditorState, ContentState, convertFromHTML } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import { convertToHTML } from 'draft-convert';
import DOMPurify from 'dompurify';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import Parser from 'html-react-parser';
export default function SinglePost() {
const location = useLocation();
const path = location.pathname.split("/")[2];
const [post, setPost] = useState({});
const PF = "http://localhost:5000/images/";
const { user } = useContext(Context);
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [updateMode, setUpdateMode] = useState(false);
useEffect(() => {
const getPost = async () => {
const res = await axios.get("/posts/" + path);
setPost(res.data);
setTitle(res.data.title);
setDesc(res.data.desc);
};
getPost();
}, [path]);
const handleDelete = async () => {
try {
await axios.delete(`/posts/${post._id}`, {
data: { username: user.username },
});
window.location.replace("/");
} catch (err) {}
};
// updating post
const handleUpdate = async () => {
try {
await axios.put(`/posts/${post._id}`, {
username: user.username,
title,
desc,
});
setUpdateMode(false)
} catch (err) {}
};
const [editorState, setEditorState] = useState(
() => EditorState.createWithContent(
ContentState.createFromBlockArray(
convertFromHTML(desc)
)
),
);
const [convertedContent, setConvertedContent] = useState(null);
const handleEditorChange = (state) => {
setEditorState(state);
convertContentToHTML();
}
const convertContentToHTML = () => {
let currentContentAsHTML = convertToHTML(editorState.getCurrentContent());
setConvertedContent(currentContentAsHTML);
setDesc(currentContentAsHTML);
}
const createMarkup = (html) => {
return {
__html: DOMPurify.sanitize(html)
}
}
return (
<div className="singlePost">
<div className="singlePostWrapper">
{post.photo && (
<img src={PF + post.photo} alt="" className="singlePostImg" />
)}
{updateMode ? (
<input
type="text"
value={title}
className="singlePostTitleInput"
autoFocus
onChange={(e) => setTitle(e.target.value)}
/>
) : (
<h1 className="singlePostTitle">
{title}
{post.username === user?.username && (
<div className="singlePostEdit">
<i
className="singlePostIcon far fa-edit"
onClick={() => setUpdateMode(true)}
></i>
<i
className="singlePostIcon far fa-trash-alt"
onClick={handleDelete}
></i>
</div>
)}
</h1>
)}
<div className="singlePostInfo">
<span className="singlePostAuthor">
Author:
<Link to={`/?user=${post.username}`} className="link">
<b> {post.username}</b>
</Link>
</span>
<span className="singlePostDate">
{new Date(post.createdAt).toDateString()}
</span>
</div>
{updateMode ? (
// <textarea
// className="singlePostDescInput"
// value={desc}
// onChange={(e) => setDesc(e.target.value)}
// />
<Editor
contentState={desc}
editorState={editorState}
onEditorStateChange={handleEditorChange}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
/>
) : (
<p className="singlePostDesc">{Parser(desc)}</p>
)}
{updateMode && (
<button className="singlePostButton" onClick={handleUpdate}>
Update
</button>
)}
</div>
</div>
);
}
I want to display desc which is saved in MongoDB database when the user clicks on update button.
The following part is what I tried to do but didn't work.
const [editorState, setEditorState] = useState(
() => EditorState.createWithContent(
ContentState.createFromBlockArray(
convertFromHTML(desc)
)
),
);
I am getting warning in this:
react.development.js:220 Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the r component.
Please help
I'm fairly new to hooks as well as useContext, I'm attempting to update onClick from a child component and keep running into the error 'setPokemonId' is not a function, or.. it just doesn't do anything at all.
PokedexContext.js
import React, { useState, useEffect } from "react";
import axios from "axios";
const PokedexContext = React.createContext([{}, () => {}]);
const PokedexProvider = (props) => {
const [state, setState] = useState({});
const [loading, setLoading] = useState(true);
let [error, setError] = useState(false);
let [pokemonId, setPokemonId] = useState(10); //807 max
useEffect(() => {
setLoading(true);
setError(false);
axios
.get(`https://pokeapi.co/api/v2/pokemon/${pokemonId}`)
.then((res) => {
setState(res.data, loading);
setLoading(false);
})
.catch((err) => {
setLoading(false);
if (err.response) {
// pokemon not found
setError("Response");
} else if (err.request) {
// api error
setError("Request");
} else {
// everything else
setError(true);
}
});
}, [pokemonId]);
return (
<PokedexContext.Provider
value={[
state,
setState,
error,
loading,
setLoading,
pokemonId,
setPokemonId,
]}
>
{props.children}
</PokedexContext.Provider>
);
};
export { PokedexContext, PokedexProvider };
App.js
import React from "react";
import { PokedexProvider } from "../../context/PokedexContext";
import Pokedex from "../Pokedex";
const Landing = () => {
return (
<PokedexProvider>
<main className="container">
<Pokedex />
</main>
</PokedexProvider>
);
};
export default Landing;
Pokedex.js
import React, { useState, useContext } from "react";
import pokedex from "../assets/pokedex.png";
import PokedexScreen from "./PokedexScreen";
import errorHandling from "../utils/errorHandling";
import { PokedexContext } from "../context/PokedexContext";
import spinner from "../assets/pika-load.gif";
const Pokedex = () => {
const [state, setState, error, loading, setPokemonId, pokemonId] = useContext(
PokedexContext
);
const [power, setPower] = useState(false);
const [shinyDisplay, setShinyDisplay] = useState(false);
console.log(pokemonId);
return (
<div
alt="Pokedex"
data-testid="Pokedex"
className="pokedex"
style={{ backgroundImage: `url(${pokedex})` }}
>
<button className="pokedex--onButton" onClick={() => setPower(!power)}>
{power ? "Off" : "On"}
</button>
{error ? (
<div className="pokedex--screen__error">{errorHandling(error)}</div>
) : power ? (
<>
{loading ? (
<img
className="pokedex--screen__load"
src={spinner}
alt="Loading..."
/>
) : (
""
)}
<button
className="pokedex--shinyButton"
onClick={() => setShinyDisplay(!shinyDisplay)}
>
S
</button>
<span>
<button
className="pokedex--negativeButton"
onClick={() => setPokemonId(pokemonId - 1)}
>
-
</button>
<button
className="pokedex--positiveButton"
// onClick={}
>
+
</button>
</span>
</>
) : (
<div className="pokedex--screen__off" />
)}
</div>
);
};
export default Pokedex;
My goal here is to update the pokemonId when clicking the positive or negative buttons, and is what is currently causing the crashes.
Issue
When you're exporting your values in Context Provider. It's in the 6th index of the array
<PokedexContext.Provider
value={[
state,
setState,
error,
loading,
setLoading,
pokemonId,
setPokemonId, (6)
]}
>
{props.children}
</PokedexContext.Provider>
But you're using from the 4th index in Pokedex.
const [state, setState, error, loading, setPokemonId, pokemonId] = useContext(
PokedexContext
);
Solution
const [
state,
setState,
error,
loading,
setLoading,
pokemonId,
setPokemonId, (6)
] = useContext(
PokedexContext
);