AxiosError : Failed to load resource: net::ERR_CONNECTION_REFUSED - javascript

I am still learning react and I am building an app with MERN Stack. I tried submitting a post from the form, which is supposed to send data to the MongoDB Atlas database and also render the post on the page. But no data is sent to the database, nor is it rendered on the page. I don't really know where the problem is coming from, but I am having an axios error and a 404 error on the Chrome browser console. I don't know if Axios is not connected to the backend or if there is a problem with my codes.
Form.js
import React, { useState, useEffect } from 'react';
import { TextField, Button, Typography, Paper } from '#material-ui/core';
import FileBase from 'react-file-base64';
import { useDispatch, useSelector } from 'react-redux';
import useStyles from './styles';
import { createPost, updatePost } from '../../actions/posts';
//GET POST CUURENT ID
const Form = ({ currentId, setCurrentId }) => {
const [postData, setPostData] = useState({creator: '', title: '', message: '', tags: '', selectedFile: ''});
const post = useSelector((state) => currentId ? state.posts.find((p) => p._id === currentId) : null);
const classes = useStyles();
const dispatch = useDispatch();
useEffect(() => {
if(post) setPostData(post);
}, [post])
const handleSubmit = (e) => {
e.preventDefault();
if(currentId) {
dispatch(updatePost(currentId, postData));
} else {
dispatch(createPost(postData));
}
clear();
}
const clear = () => {
setCurrentId(null);
setPostData({creator: '', title: '', message: '', tags: '', selectedFile: ''});
}
return (
<Paper className={classes.paper}>
<form autoComplete='off' noValidate className={`${classes.root} ${classes.form}`} onSubmit={handleSubmit}>
<Typography variant='h6'>{ currentId ? 'Edit' : 'Create' } Your Expressions</Typography>
<TextField name='creator' variant='outlined' label='Creator' fullWidth value={postData.creator} onChange={(e) => setPostData({ ...postData, creator: e.target.value })} />
<TextField name='title' variant='outlined' label='Title' fullWidth value={postData.title} onChange={(e) => setPostData({ ...postData, title: e.target.value })} />
<TextField name='message' variant='outlined' label='Message' fullWidth value={postData.message} onChange={(e) => setPostData({ ...postData, message: e.target.value })} />
<TextField name='tags' variant='outlined' label='Tags' fullWidth value={postData.tags} onChange={(e) => setPostData({ ...postData, tags: e.target.value })} />
<div className={classes.fileInput}><FileBase type="file"multiple={false} onDone={({base64}) => setPostData({ ...postData, selectedFile: base64 })} />
</div>
<Button className={classes.buttonSubmit} variant='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
<Button variant='outlined' color='primary' size='large' onClick={clear} fullWidth>Clear</Button>
</form>
</Paper>
);
}
export default Form;
Server/index.js
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js'
const app = express();
app.use('/posts', postRoutes);
app.use(bodyParser.json({ limit: "30mb", extended: true}));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true}));
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL = 'mongodb+srv://Akan-
modanwealth:aakkaann#cluster0.jvfdwah.mongodb.net/?retryWrites=true&w=majority';
const PORT = process.env.PORT || 5000;
mongoose.connect(CONNECTION_URL).then(()=>{console.log('...')})
.then(() => app.listen(PORT, () => console.log('Server running on port:
${PORT}')))
.catch((error) => console.log(error.message));
App.js
import React, { useState, useEffect } from 'react';
import { Container, AppBar, Typography, Grow, Grid } from '#material-ui/core';
import { useDispatch } from 'react-redux';
import { getPosts } from './actions/posts';
import Posts from './components/Posts/Posts';
import Form from './components/Form/Form';
import expressions from './images/expressions.jpg';
import useStyles from './styles';
const App = () => {
const [currentId, setCurrentId] = useState(null);
const classes = useStyles();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPosts);
}, [currentId, dispatch]);
return (
<Container maxWidth="lg">
<AppBar className={classes.appBar} position="static" >
<Typography className={classes.heading} variant="h2" align="center">Expressions</Typography>
<img className={classes.image} src={expressions} alt="expressions" height="80" width="60" />
</AppBar>
<Grow in>
<Container>
<Grid container justifyContent="space-between" alignItems="stretch" spacing={3}>
<Grid item xs={12} sm={7}>
<Posts setCurrentId={setCurrentId} />
</Grid>
<Grid item xs={12} sm={4}>
<Form currentId={currentId} setCurrentId={setCurrentId} />
</Grid>
</Grid>
</Container>
</Grow>
</Container>
);
}
export default App;
api/index.js
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) => axios.patch(`${url}/${id}`,
updatedPost);
routes/posts.js
import express from 'express';
import { getPosts, createPost, updatePost} from
'../controllers/posts.js';
const router = express.Router();
router.get('/', getPosts);
router.get('/', createPost);
router.patch('/:id', updatePost)
export default router;
Here is the error on the browser console

So there are a couple of things. First, you may have exposed your password in your MongoDB URI, so I'd go and change that immediately. Second, is there a reason you're running app.use("/posts", postRoutes); twice?
Lastly, it looks like you're posting to /posts, but you're not specifying a route after that. You didn't share your routes, but from the looks of it /posts uses all routes in your routes folder. You need to give a specific route, like /posts/create or something. Otherwise you're just saying making a POST request to the object with all your middleware and node.js doesn't know which middleware to use.

Related

Search using queryParams displays the correct URL, but does not filter the components

In my application, I have a form that is supposed to search for the workout components that I have displayed based on two fields: category and difficulty. When I search, I can see that the URL changes properly, but the cards are not filtered at all. They disappear. Below I have the code for the component where the search is made:
import React, {useState, useEffect} from 'react'
import {Container, Grow, Grid, Paper, AppBar,TextField,Button, TextareaAutosize} from '#material-ui/core';
import {useDispatch} from 'react-redux';
import {getWorkouts, getWorkoutsBySearch} from '../../actions/workouts';
import {useNavigate, useLocation, Navigate} from 'react-router-dom';
import ChipInput from 'material-ui-chip-input'
import Workouts from "../Workouts/Workouts";
import Pagination from '../Pagination';
import Form from "../Form/Form";
import useStyles from './styles';
function useQuery(){
return new URLSearchParams(useLocation().search);
}
function Home() {
const [currentId, setCurrentId]=useState(null);
const classes=useStyles();
const dispatch=useDispatch();
const query=useQuery();
const history=useNavigate();
const page=query.get('page')||1;
const searchQuery=query.get('searchQuery');
const [search, setSearch] = useState('');
const [category, setCategory] = useState([]);
const searchWorkout=()=>{
if(search.trim() || category){
dispatch(getWorkoutsBySearch({search, category:category.join(',')}));
history(`/workouts/search?searchQuery=${search || 'none'} & category=${category.join(',')}`)
}else{
history(`/workouts`);
}
}
useEffect(()=>{
dispatch(getWorkouts());
},[currentId, dispatch]);
const handleKeyPress=(e)=>{
if(e.keyCode===13){
searchWorkout();
}
}
const handleAdd=(categ)=>setCategory([...category,categ]);
const handleDelete=(categoryToDelete)=>setCategory(category.filter((categ)=>categ!==categoryToDelete));
const user = JSON.parse(localStorage.getItem("profile"));
return (
<Grow in>
<Container maxWidth="xl">
<Grid className={classes.gridContainer} container justifyContent="space-between" alignItems='stretch' spacing={3}>
<Grid item xs={12} sm={6} md={9}>
<Workouts setCurrentId={setCurrentId}/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<AppBar className={classes.appBarSearch} position="static" color="inherit">
<TextField
name="search"
variant="outlined"
label="Search workouts"
onKeyPress={handleKeyPress}
fullWidth
value={search}
onChange={(e)=>setSearch(e.target.value)}
/>
<ChipInput
style={{margin:'10px 0'}}
value={category}
onAdd={handleAdd}
onDelete={handleDelete}
label="Search Category"
variant="outlined"
/>
<Button onClick={searchWorkout} className={classes.searchButton} variant="contained" color="primary">Search</Button>
</AppBar>
{
user?.result?.email.endsWith('admin.com')?
<>
<Form currentId={currentId} setCurrentId={setCurrentId}/>
<Paper className={classes.pagination} elevation={6}>
<Pagination page={page}/>
</Paper>
</>
:<></>
}
</Grid>
</Grid>
</Container>
</Grow>
)
}
export default Home
The backend request is the following one:
export const getWorkoutsBySearch = async (req, res) => {
const { searchQuery, category } = req.query;
try {
const difficulty = new RegExp(searchQuery, "i");
const workouts = await WorkoutMessage.find({ $or: [ { category }, { difficulty } ]});
res.json({ data: workouts });
console.log(workouts);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
The search in the actions folder is this one:
export const getWorkouts=()=> async (dispatch)=>{
try{
const data=await api.fetchWorkouts();
dispatch({type:FETCH_ALL,payload:data});
}catch(error){
console.log(error);
}
}
export const getWorkoutsBySearch=(searchQuery)=>async(dispatch)=>{
try{
const {data: {data}}=await api.fetchWorkoutsBySearch(searchQuery);
dispatch({type:FETCH_BY_SEARCH,payload:data});
}catch(error){
console.log(error);
}
}
The reducer is below:
case FETCH_BY_SEARCH:
return action.payload;
Could you help me solve this?

Strange State / UseEffect Behaviour using NextJS Link

I am experiencing so really strange behaviour in this personal project i am doing. In short it is a recipe website, with buttons at the top that direct to different pages that ultimately query firebase and pull down a query.
Index.js File - Queries Firestore passes props to FoodCard.js to Render a list of all recipes
breakfast.js - Queries Firestore with a filter and passes same props down (with different results) to FoodCard.js
Behaviour
When i click on Breakfast JS, it brings up my list of filtered results correctly, however when i click my Next Link "Welcome to the Family Heirloom" to return to the index the first click doesnt respond, then the second click returns home, but with the filtered breakfast result concatonated with all the original results (effectively causing duplicates)Index on First Render
Breakfast filter successful
index with the now duplicate pancake result
I have messed about wondering if useEffect is not getting triggered which you may see in the code, but that didnt seem to work, so at a loss
Index.js
import { React, useEffect, useState } from 'react'
import { useRouter } from 'next/dist/client/router'
import { useTheme } from '#mui/material/styles'
import { makeStyles } from '#mui/styles'
import Modal from '#mui/material/Modal'
import FoodCard from '../src/ui/FoodCard.js'
import firebase from '../firebase/initFirebase'
import Box from '#mui/material/Box'
import Typography from '#mui/material/Typography'
const useStyles = makeStyles(theme => ({
mainContainer: {
}
}))
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: 'red',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
export default function CookBook() {
const router = useRouter();
const { id } = router.query;
const classes = useStyles()
const theme = useTheme()
const [loading, setLoading] = useState(true);
const [recipes, setRecipes] = useState([]);
const [open, setOpen] = useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
useEffect(() => {
const getRecipesFromFirebase = [];
const subscriber = firebase.firestore()
.collection("recipes")
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(querySnapshot)
getRecipesFromFirebase.push({
...doc.data(), //spread operator
key: doc.id, // `id` given to us by Firebase
});
});
setRecipes(getRecipesFromFirebase);
console.log(recipes);
setLoading(false);
});
return () => subscriber();
}, [loading, router.events]); // empty dependencies array => useEffect only called once
if (loading) {
return (
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Typography id="modal-modal-title" variant="h6" component="h2">
Loading Data
</Typography>
</Box>
</Modal>)
}
return (
<FoodCard recipes={recipes} />
)
}
_app.js
import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider } from '#mui/material/styles';
import CssBaseline from '#mui/material/CssBaseline';
import { CacheProvider } from '#emotion/react';
import theme from '../src//ui/theme';
import createEmotionCache from '../src/createEmotionCache';
import Header from '../src/ui/Header';
import Grid from '#mui/material/Grid'
import Typography from '#mui/material/Typography'
import { Link as MUILink } from '#mui/material/'
import NextLink from 'next/link'
// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
export default function MyApp(props) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
return (
<CacheProvider value={emotionCache}>
<Head>
<meta name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
<Header />
<Grid container justify="center" alignItems="center" direction="column" >
<Grid item>
<NextLink href="/" passHref>
<MUILink underline="none" color="secondary" variant="h1">
Welcome To the Family Heirloom
</MUILink>
</NextLink>
</Grid>
</Grid>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
);
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
emotionCache: PropTypes.object,
pageProps: PropTypes.object.isRequired,
};
Breakfast.js
import { React, useEffect, useState } from 'react'
import FilterMains from '../../src/ui/FilterMains'
import { useRouter } from 'next/dist/client/router'
import FoodCard from '../../src/ui/FoodCard'
import {
getFirestore, collection, query, where, onSnapshot
} from 'firebase/firestore'
const Breakfast = () => {
const router = useRouter();
const { id } = router.query;
const [breakfastloading, setBreakfastLoading] = useState(true);
const [breakfastRecipe, setBreakfastRecipe] = useState([]);
const db = getFirestore()
const docRef = collection(db, 'recipes')
//Query
const q = query(docRef, where("category", "==", 'Breakfast'))
useEffect(() => {
const getBreakfastFromFirebase = [];
onSnapshot(q, (snapshot) => {
snapshot.docs.forEach((doc) => {
getBreakfastFromFirebase.push({ ...doc.data() })
})
setBreakfastRecipe(getBreakfastFromFirebase)
setBreakfastLoading(false)
console.log(breakfastRecipe)
})
}, [breakfastloading, router.events]);
if (breakfastloading) {
return (
<h2>Loading Data</h2>
)
}
return (
<FoodCard recipes={breakfastRecipe} />
// <FoodCard recipes={recipes} />
)
}
export default Breakfast
FoodCard.js
import React from 'react'
import Card from '#mui/material/Card'
import CardHeader from '#mui/material/CardHeader';
import CardMedia from '#mui/material/CardMedia';
import Grid from '#mui/material/Grid'
import Container from '#mui/material/Container';
import Link from 'next/link'
import CardActionArea from '#mui/material/CardActionArea';
function FoodCard(props) {
return (
<div>
<Container>
< Grid container justify="center" alignItems="center" direction="row" >
<Grid container spacing={2}>
{props.recipes.map((recipe) => (
<Link href={`/recipes/${recipe.key}`} passHref>
<Grid key={recipe.id} item xs={12} md={6}>
<Card elevation={3} sx={{ maxWidth: 400 }}>
<CardActionArea>
<CardHeader
titleTypographyProps={{ fontWeight: "Bold" }}
title={recipe.title}
subheader={recipe.description}
/>
<CardMedia
component="img"
height="194"
image="/assets/comingsoon.jpg"
alt="Mac and Cheese"
/>
</CardActionArea>
</Card>
</Grid>
</Link>
))}
</Grid>
</Grid >
</Container>
</div>
)
}
export default FoodCard
Cracked it, although i can't fully explain why. In my learning i used two different methods for interfacing with firebase. The first method on the index page was what i would call the older way. The second method i used was in all of my other files, specific to interfacing with Version 9 of Firebase.
from this:
const subscriber = firebase.firestore()
.collection("recipes")
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(querySnapshot)
getRecipesFromFirebase.push({
...doc.data(), //spread operator
key: doc.id, // `id` given to us by Firebase
});
});
to this:
let getRecipesFromFirebase = [];
getDocs(colRef)
.then((snapshot) => {
let getRecipesFromFirebase = [];
snapshot.docs.forEach((doc) => {
getRecipesFromFirebase.push({ ...doc.data(), key: doc.id })
})
setRecipes(getRecipesFromFirebase);
console.log(recipes);
setLoading(false);
})
.catch(error => {
console.log(error.message)
})
Would love somebody more knowledgable (3 months into React) than myself to tell me as to why though.

Syntax error: Unexpected token by using firebase

I am now following this youtube video to develop an Instagram clone app by using React with firebase.
The error occurred at the point below, on the video at 2:36:29.
It says "Syntax error: Unexpected token (93:12)"
{user?.displayName ? (
<ImageUpload username={user.displayName} />
) : (
<h3>sorry you need to login to upload</h3>
)}
what I tried
・Just put <ImageUpload username={user.displayName} />
=> I got 「firebase is not defined」 error on the other js file.
・put "user.displayName" instead of "user?.displayName" (? is erased)
=> more complicated error occur that "TypeError: Cannot read properties of null (reading 'displayName')"
・Put {user ? (<ImageUpload username={user.displayName} />) : (<h3>Sorry you need to login !!</h3>)} eraced displayName
=> only visual works(surely, the username is not given in this case)
Adobe three tries, I guess displayName is the main point to solve the issue...
If you are good at React.js or you have seen the same error, please give me advice.
Whole App.js codes↓
App.js
import React, { useState, useEffect } from 'react'
import './App.css';
import Post from './Post';
import { db, auth } from './firebase';
import Modal from '#mui/material/Modal';
import Box from '#mui/material/Box';
import Button from '#mui/material/Button';
import Input from '#mui/material/Input';
//import Typography from '#mui/material/Typography';
import ImageUpload from './ImageUpload';
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: 'background.paper',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
function App() {
const [posts, setPosts] = useState([]);
const [open, setOpen] = React.useState(false);
const [openSignIn, setOpenSignIn] = useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((authUser) => {
if (authUser) {
//User has logged IN
console.log(authUser);
setUser(authUser);
//↑ is keep user logged in after refresh
} else {
//User has logged OUT
setUser(null);
}
})
return () => {
//perform some cleanup actions
unsubscribe(null);
}
}, [user, username]);
//useEffect => where the code runs, last []) means the code runs only once
useEffect(() => {
db.collection('posts').onSnapshot(snapshot => {
setPosts(snapshot.docs.map(doc => ({
id: doc.id,
post: doc.data()
})));
})
}, []);
//signup func
const signup = (event) => {
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((authUser) => {
return authUser.user.updateProfile({
displayName: username
})
})
.catch((error) => alert(error.message));
setOpen(false);
}
//signin func
const signin = (event) => {
event.preventDefault();
auth
.signInWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
setOpenSignIn(false);
}
return (
<div className="app">
{user.displayName ? (
<ImageUpload username={user.displayName} />
) : (
<h3>sorry you need to login to upload</h3>
)}
<div className="app__header">
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt="HeaderImage"
/>
{user ? (
<Button onClick={() => auth.signOut()}>Logout</Button>
) : (
<div className="app__loginContainer">
<Button onClick={() => setOpenSignIn(true)}>SignIn</Button>
<Button onClick={() => setOpen(true)}>SignUp</Button>
</div>
)}
</div>
<Modal
open={open}
onClose={() => setOpen(false)}
>
<Box sx={style}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt="HeaderImage"
/>
</center>
<Input
type="text"
placeholder="username"
//at first, ↓ was value={username}, but typing cannot be shown on the screen in that case,
//https://stackoverflow.com/questions/34006333/cant-type-in-react-input-text-field
//↑is the trouble shooting, which says try defaultValue instead of value(V is capital).
defaultValue={username}
onChange={(e) => setUsername(e.target.value)}
/>
<Input
type="text"
placeholder="email"
defaultValue={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
type="text"
placeholder="password"
defaultValue={password}
onChange={(e) => setPassword(e.target.value)}
/>
<center>
<Button type="submit" onClick={signup}>SignUp</Button>
</center>
</form>
</Box>
</Modal>
<Modal
//signupModal
open={openSignIn}
onClose={() => setOpenSignIn(false)}
>
<Box sx={style}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt="HeaderImage"
/>
</center>
<Input
type="text"
placeholder="email"
defaultValue={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
type="text"
placeholder="password"
defaultValue={password}
onChange={(e) => setPassword(e.target.value)}
/>
<center>
<Button type="submit" onClick={signin}>SignIn</Button>
</center>
</form>
</Box>
</Modal>
<h1>TEST</h1>
{/* header */}
{
posts.map(({ id, post }) => (
<Post username={post.username} caption={post.caption} imageUrl={post.imageUrl} />
))
}
{/* post */}
{/* post */}
</div >
);
}
export default App;
Here↓ is ImageUpload.js which I got firebase is not defined when I erase the? mark from ImageUpload tag,,,,
firebase is not defined from this line↓
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
ImageUpload.js
import React, { useState } from 'react';
import Button from '#mui/material/Button';
import { storage, db } from "./firebase";
import firebase from 'firebase/app';
function ImageUpload(username) {
const [image, setImage] = useState(null);
const [url, setUrl] = useState("");
const [progress, setProgress] = useState(0);
const [caption, setCaption] = useState('');
const handleChange = (e) => {
if (e.target.files[0]) {
setImage(e.target.files[0])
}
};
const handleUpload = () => {
const uploadTask = storage.ref('images/${image.name}').put(image);
uploadTask.on(
"state_change",
(snapshot) => {
//progress function
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
//error function
console.log(error);
alert(error.message);
},
() => {
//complete func
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
//post image inside DB
db.collection("posts").add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
caption: caption,
imageUrl: url,
username: username
});
setProgress(0);
setCaption("");
setImage(null);
})
}
)
}
return (
<div>
{/* I want to have .... */}
{/* caption input */}
{/* file picker */}
{/* Post button */}
<progress value={progress} max="100" />
<input type="text" placeholder="enter a caption.." onChange={event => setCaption(event.target.value)} />
<input type="file" onChange={handleChange} />
<Button onClick={handleUpload}>
upload
</Button>
</div >
)
}
export default ImageUpload
To be safe here ↓ is firebase.js(privacy info are shown as ***)
firebase.js
import firebase from "firebase";
const firebaseApp = firebase.initializeApp({
apiKey: "***",
authDomain: "***.firebaseapp.com",
projectId: "***",
storageBucket: "***.appspot.com",
messagingSenderId: "*****",
appId: "****",
measurementId: "****"
})
const db = firebase.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export { db, auth, storage };
And index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Moreover, firebase version is 8.10.0, using MacBook air intel one OS BigSur

Getting 'Aw snap! : error code: Out of memory'

I was trying to build simple react-redux app using reducers. But every time I open the website it is popping up this error and I couldn't open the console. I tried to clean cookies and caches but no help.
Whenever I change <Posts /> and <Form /> to simple <h1> tags it works perfectly fine, but I can't find the bug.
My code in
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { reducers } from './reducers/index.js';
import App from './App';
const store = createStore(reducers, compose(applyMiddleware(thunk)));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);
App.js
import React,{ useEffect, useState } from 'react';
import { Container, AppBar, Typography, Grid, Grow } from '#material-ui/core';
import { useDispatch } from 'react-redux';
import Posts from '../src/components/Posts';
import Form from './components/form';
import { getPosts } from './actions/action';
function App() {
const [currentId, setCurrentId] = useState();
const dispatch = useDispatch();
useEffect(() =>{
dispatch(getPosts());
},[dispatch, currentId]);
return (
<div>
<Container maxWidth='lg'>
<AppBar position='static' color='inherit'>
<Typography variant='h2' align='center' >SimplePRATICE</Typography>
</AppBar>
<Grow in>
<Container>
<Grid container justify='space-between' alignItems='stretch' spacing={3}>
<Grid item xs={12} sm={4}>
<Form currentId={currentId} setCurrentId={setCurrentId} />
</Grid>
</Grid>
</Container>
</Grow>
</Container>
</div>
);
}
export default App;
form.js
import React, { useEffect, useState } from 'react';
import { Paper, Button, TextField, Typography } from '#material-ui/core';
import { useSelector, useDispatch } from 'react-redux';
import { createPost, updatePost } from '../actions/action.js';
function Form({ currentId, setCurrentId }) {
const [postData, setpostData] = useState({ name:'', message:'' });
const post = useSelector((state) => (currentId ? state.posts.find((message) => message._id === currentId ) :null ));
const dispatch = useDispatch();
useEffect(() => {
if (post) setpostData(post);
}, [post]);
const clear = () =>{
setCurrentId(0);
setpostData({ name: '', message:''});
};
const handleSubmit = async (e) => {
e.preventDefault();
if (currentId === 0){
dispatch(createPost(postData));
}else{
dispatch(updatePost(currentId, postData));
}
clear();
};
return (
<Paper>
<Form onSubmit={handleSubmit}>
<Typography>Creating Post</Typography>
<TextField name="name" variant="outlined" label="Name" fullWidth value={postData.name} onChange={(e) => setpostData({ ...postData, name: e.target.value })} />
<TextField name="message" variant="outlined" label="Message" fullWidth multiline rows={4} value={postData.message} onChange={(e) => setpostData({ ...postData, message: e.target.value })} />
<Button varient='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
</Form>
</Paper>
)
}
export default Form
Posts.js
import React from 'react';
import Post from './post.js';
import { Grid } from '#material-ui/core';
import { useSelector } from 'react-redux';
function Posts({ setCurrentId }) {
const posts = useSelector((state) => state.posts);
return (
<Grid container alignItems='stretch' spacing={3}>
{posts.map((post) => (
<Grid key={post._id} item xs={12} sm={6} md={6}>
<Post post={post} setCurrentId={setCurrentId} />
</Grid>
))}
</Grid>
)
}
export default Posts
Post.js
import React from 'react';
import { Card, CardActions, CardContent, Button, Typography } from '#material-ui/core/';
import DeleteIcon from '#material-ui/icons/Delete';
import MoreHorizIcon from '#material-ui/icons/MoreHoriz';
import { useDispatch } from 'react-redux';
import { deletePost } from '../actions/action.js';
function Post({ post, setCurrentId }) {
const dispatch = useDispatch();
return (
<Card>
<div>
<Typography varient='h6'>{post.name}</Typography>
</div>
<di>
<Button style={{ color:'white' }} size='small' onClick={()=> setCurrentId(post._id)}><MoreHorizIcon fontSize='default' /></Button>
</di>
<CardContent>
<Typography vaarient='body2' color='textSecondary' component='p'>{post.message}</Typography>
</CardContent>
<CardActions>
<Button size='small' color='primary' onClick={()=> dispatch(deletePost(post._id))} ><DeleteIcon fontSize='small'>Delete</DeleteIcon></Button>
</CardActions>
</Card>
)
}
export default Post
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) => axios.patch(`${url}/${id}`, updatedPost);
export const deletePost = (id) => axios.delete(`${url}/${id}`);
Your Form component renders itself:
return (
<Paper>
<Form onSubmit={handleSubmit}>
<Typography>Creating Post</Typography>
<TextField name="name" variant="outlined" label="Name" fullWidth value={postData.name} onChange={(e) => setpostData({ ...postData, name: e.target.value })} />
<TextField name="message" variant="outlined" label="Message" fullWidth multiline rows={4} value={postData.message} onChange={(e) => setpostData({ ...postData, message: e.target.value })} />
<Button varient='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
</Form>
</Paper>
)
I think you meant <form> which is not a react component.
return (
<Paper>
<form onSubmit={handleSubmit}>
<Typography>Creating Post</Typography>
<TextField name="name" variant="outlined" label="Name" fullWidth value={postData.name} onChange={(e) => setpostData({ ...postData, name: e.target.value })} />
<TextField name="message" variant="outlined" label="Message" fullWidth multiline rows={4} value={postData.message} onChange={(e) => setpostData({ ...postData, message: e.target.value })} />
<Button varient='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
</form>
</Paper>
)
You must have selected a wrong element in your html which is not going on well with the code.
Hence please check all the elements properly.
If it is a functional component , check it again.
I had the same issue and it got resolved.

Why won't my axios request return the proper data?

I have an api running at the url used in my axios instance. A route is defined for login that returns JWT access and refresh tokens if valid credentials are provided. I can test it using postman and everything works great, but in my app using axios no tokens or error gets returned even with valid credentials. The API is setup for cors also and is running live.
here is the axios instance:
import axios from 'axios';
const url = NOT SHOWN;
const axiosInstance = axios.create({
baseURL: url,
headers: {
'Content-Type': 'application/json',
},
});
export default axiosInstance;
here is the basic login component:
import React, { Component } from 'react';
import { Link as RouteLink, Redirect } from 'react-router-dom';
import axiosInstance from '../../axiosInstance';
//material ui
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import TextField from '#material-ui/core/TextField';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import Checkbox from '#material-ui/core/Checkbox';
import Link from '#material-ui/core/Link';
import Grid from '#material-ui/core/Grid';
import Typography from '#material-ui/core/Typography';
import { makeStyles } from '#material-ui/core/styles';
import Container from '#material-ui/core/Container';
class Login extends Component {
state = {
email: '',
password: '',
isAuthenticated: false,
};
login(email, password) {
const data = {
email: email,
password: password,
};
axiosInstance
.post('/login', data)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
}
onSubmit = (e) => {
const { email, password } = this.state;
this.login(email, password);
};
onChange = (e) => this.setState({ [e.target.name]: e.target.value.trim() });
render() {
if (this.state.isAuthenticated) {
return <Redirect to='/' />;
}
return (
<Container component='main' maxWidth='xs' style={{ marginTop: '75px' }}>
<CssBaseline />
<div>
<Typography component='h1' variant='h3' align='center'>
Login
</Typography>
<form noValidate>
<TextField
variant='outlined'
margin='normal'
required
fullWidth
id='email'
label='Email Address'
name='email'
autoComplete='email'
autoFocus
onChange={this.onChange}
/>
<TextField
variant='outlined'
margin='normal'
required
fullWidth
name='password'
label='Password'
type='password'
id='password'
autoComplete='current-password'
onChange={this.onChange}
/>
<FormControlLabel
control={<Checkbox value='remember' color='primary' />}
label='Remember me'
/>
<Button
type='submit'
fullWidth
variant='contained'
color='primary'
//className={classes.submit}
onClick={this.onSubmit}
>
LOGIN
</Button>
<Grid container>
<Grid item xs>
<Link variant='body2'>Forgot password?</Link>
</Grid>
<Grid item>
<Link component={RouteLink} to={'/signup'} variant='body2'>
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
}
export default Login;
'''
I believe the login function is not defined properly so it is not being called. Please try using a function expression:
login = (email, password) => {
const data = {
email: email,
password: password,
};
axiosInstance
.post('/login', data)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
}
onSubmit = (e) => {
const { email, password } = this.state;
login(email, password);
};

Categories