I'm hoping someone can help me figure out what I'm doing wrong. I have some code in a React component AddProject that looks like this.
import React, { useState, useContext } from "react";
import "./addproject.css";
import UserContext from "../../UserContext";
import saveProject from '../../features/saveProject';
function AddProject() {
const handleSaveProject = () => {
const projectData = {
[userEmail]: {
clientName: clientName,
clientEmail: clientEmail,
stages: stages,
}
}
console.log(userEmail, projectData);
saveProject(projectData)
//etc
I alsa have another component/method saveProject that I want to pass some props to and make a post request with Axios.
import React, { useState } from "react";
import axios from "axios";
const saveProject = (projectData) => {
const handleSubmit = (event) => {
event.preventDefault();
axios
.post("[http://localhost:4000/users](http://localhost:4000/users)", projectData)
.then((res) => console.log(res))
.catch((err) => console.error(err));
};
return (null);
};
export default saveProject;
I keep getting this error telling me it isn't a function. I've tried changing the import statement to {saveProject} and doing export const instead, but that didn't help. ChatGPT can't figure it out either. Any ideas?
2AddProject.jsx:86 Uncaught TypeError: _features_saveProject__WEBPACK_IMPORTED_MODULE_3___default(...) is not a function
at handleSaveProject (AddProject.jsx:86:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070:1)
at executeDispatch (react-dom.development.js:8243:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:8275:1)
at processDispatchQueue (react-dom.development.js:8288:1)
at dispatchEventsForPlugins (react-dom.development.js:8299:1)
at react-dom.development.js:8508:1
Figured it out, I somehow didn't save or did or something, but it wasn't being exported. Restarting the server didn't help, but when I restarted my computer the error showed for some reason. Thank you everyonev
Related
Can anyone please see what is wrong here? Started building an app and got stuck in the beginning...
Getting this error when triggering loginToSpotify():
TypeError: _services_login__WEBPACK_IMPORTED_MODULE_0__.login is not a function
at loginToSpotify (Login.js:6:1)
at onClick (Login.js:15:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
at processDispatchQueue (react-dom.development.js:9086:1)
at dispatchEventsForPlugins (react-dom.development.js:9097:1)
index.js
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
App.js
import Login from './pages/Login'
const App = () => {
return (
<>
<Login />
</>
)
}
export default App
Login.js
import loginService from '../services/login'
const Login = () => {
const loginToSpotify = async () => {
try {
const response = await loginService.login()
} catch (err) {
console.log(err)
}
}
return (
<>
<div>
<button onClick={() => loginToSpotify()}>Login using Spotify</button>
</div>
</>
)
}
export default Login
login.js
import axios from 'axios'
const login = async () => {
const response = await axios.post('/login')
return response.data
}
export default { login }
Sending a fetch request to this API, though as the title states, keep getting unexpected end of input and I can't figure out why. Any solutions?
import './App.css';
import React, {useEffect, useState} from 'react';
const ART_API = "https://api.harvardartmuseums.org"
function App() {
const [anime ,setAnime] = useState([])
useEffect(() => {
fetch(ART_API, {mode: 'no-cors'})
.then((res) => res.json())
.then((data) => { console.log(data)})
}, []);}
Down below is the code where I am getting an error on. This is a WhatsApp clone using react JS and firebase as a server that I am making and I am following the instructions to the teeth but for some reason, I can't fix this annoying bug! I defined db and imported it as you see below but it is still giving me an error. Plz, help! If you need me to clarify or have any other questions please let me know!
enter image description here
import React, { useEffect, useState } from 'react'
import{Avatar, IconButton} from "#material-ui/core";
import DonutLargeIcon from "#material-ui/icons/DonutLarge";
import ChatIcon from "#material-ui/icons/Chat";
import MoreVertIcon from "#material-ui/icons/MoreVert";
import{SearchOutlined} from "#material-ui/icons";
import SidebarChat from "./SidebarChat";
import "./Sidebar.css";
import db from "./firebase";
function Sidebar() {
const [rooms, setRooms] = useState([]);
useEffect(() => {
db.collection("rooms").onSnapshot((snapshot) =>
setRooms(snapshot.docs.map((doc) =>({
id: doc.id,
data: doc.data(),
}))
)
);
}, []);
I went into the firebase.js file and changed the export from the following:
export default {db};
To the following and it removed the error for me:
export default db;
The issue was caused by the brackets in my case.
I'm creating a logout link in React using context hooks and reducer dispatch. I'm getting an error after i log-in.
I'm using node, express, and mongoose in the backend.
Here is Logout.js:
import React ,{useState, useContext}from 'react';
import {useHistory,Redirect, Link} from 'react-router-dom'
import { AuthContext } from '../../contexts/AuthContext';
import axios from 'axios'
const Logout =()=>{
const {authLog,dispatch} = useContext(AuthContext)
axios.get('http://localhost:2000/apiEndpoint/CREATE/user/logout',{withCredentials:true}).then((res)=>{
if(res.data==='Logout Success'){
dispatch({type: 'LOGOUT'});
}
}).catch((err)=>{
console.log(err)
})
return(
<div >
<h1>You are logged out!!!!</h1>
{<Redirect to='/' />}
</div>
)
}
export default Logout
Here is AuthReducer.js:
import React from 'react';
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN":
localStorage.setItem("user", JSON.stringify(action.payload.user));
localStorage.setItem("token", JSON.stringify(action.payload.token));
return {
...state,
isAuthenticated: true,
user: action.payload.user,
token: action.payload.token
};
case "LOGOUT":
localStorage.clear();
return {
...state,
isAuthenticated: false,
user: null
};
default:
return state;
}
};
export default AuthReducer
Here is Blog.js:
[NOTE]: I'm getting an error after the login page when it redirects me to the Blog.js component after successful login.
import React, { Component } from 'react';
import ArticleCard from '../ArticleCard'
import '../CSS/Blog.css'
import Sidebar from './Sidebar';
const axios = require('axios').default;
class Blog extends Component{
state={
}
render(){
return (
<div className='blog-grid'>
<div className='ninetyPer'>
<ArticleCard />
</div>
<div className='tenPer'>
<Sidebar />
</div>
</div>
)
}
}
export default Blog
Here is Sidebar.js:
import React ,{useState, useContext}from 'react';
import {useHistory,Redirect, Link} from 'react-router-dom'
import { AuthContext } from '../../contexts/AuthContext';
import '../CSS/Sidebar.css'
const Sidebar =()=>{
const {authLog,dispatch} = useContext(AuthContext)
var userOBJ=(authLog.isAuthenticated)?(JSON.parse(authLog.user.userLocal)):null;
console.log('AuthLOg:',userOBJ)
return(
<div className='sidebar'>
{userOBJ!=null?(<h4>Hello {userOBJ.username}!</h4>):(<h4>You are not logged in</h4>)}
{authLog.isAuthenticated?(<Link to='/user/logout'><h5>Logout</h5></Link>):''}
<hr />
</div>
)
}
export default Sidebar
In the browser console, there are 3 error including the one in the title:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Sidebar (Sidebar.js:14)
at renderWithHooks (react-dom.development.js:14803)
at mountIndeterminateComponent (react-dom.development.js:17482)
at beginWork (react-dom.development.js:18596)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at beginWork$1 (react-dom.development.js:23203)
at performUnitOfWork (react-dom.development.js:22154)
at workLoopSync (react-dom.development.js:22130)
at performSyncWorkOnRoot (react-dom.development.js:21756)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at scheduleUpdateOnFiber (react-dom.development.js:21199)
at dispatchAction (react-dom.development.js:15660)
at Login.js:39
index.js:1 The above error occurred in the <Sidebar> component:
in Sidebar (at Blog.js:29)
in div (at Blog.js:28)
in div (at Blog.js:21)
in Blog (created by Context.Consumer)
in Route (at App.js:43)
in AuthContextProvider (at App.js:38)
in Switch (at App.js:37)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:33)
in div (at App.js:31)
in App (at src/index.js:9)
in StrictMode (at src/index.js:8)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit //fbReactLink to learn more about error boundaries.
console.<computed> # index.js:1
react-dom.development.js:248 Uncaught (in promise) Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See //fbReactLink for more information.
at Object.invokeGuardedCallbackDev (react-dom.development.js:248)
at invokeGuardedCallback (react-dom.development.js:292)
at beginWork$1 (react-dom.development.js:23203)
at performUnitOfWork (react-dom.development.js:22154)
at workLoopSync (react-dom.development.js:22130)
at performSyncWorkOnRoot (react-dom.development.js:21756)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at scheduleUpdateOnFiber (react-dom.development.js:21199)
at dispatchAction (react-dom.development.js:15660)
at Login.js:39
If you need me to post the other components as well please do let me know and I will update this post.
A cross-origin error occurs when the server is being accessed through a port or host other than itself (React rather than localhost or www.websitename.com)
To quickly fix this, add this to your React package.json:
"proxy": "http://localhost:2000"
You can now access the server files using "/" instead of "http://localhost:2000" as React is using the proxy instead of an external link.
Your code in Logout.js line 7 should now be:
axios.get('/apiEndpoint/CREATE/user/logout',{withCredentials:true}).then((res)=>{
Just remember to change your proxy when in development to whatever your base website name is E.G. (www.website.com)
EDIT: for convenience, the Logout.js full code can be replaced with:
import React ,{useState, useContext}from 'react';
import {useHistory,Redirect, Link} from 'react-router-dom'
import { AuthContext } from '../../contexts/AuthContext';
import axios from 'axios'
const Logout =()=>{
const {authLog,dispatch} = useContext(AuthContext)
axios.get('/apiEndpoint/CREATE/user/logout',{withCredentials:true}).then((res)=>{
if(res.data==='Logout Success'){
dispatch({type: 'LOGOUT'});
}
}).catch((err)=>{
console.log(err)
})
return(
<div >
<h1>You are logged out!!!!</h1>
{<Redirect to='/' />}
</div>
)
}
export default Logout
If this doesn't work, try our the cars npm package at https://www.npmjs.com/package/cors
Simply import it and run the function right after initializing app as follows
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
IMPORTANT NOTE -- make sure to pass in an object like this {origin: YOUR_REACT_LOCALHOST_URI} when using cors in production.
You can read up on this in the cors npm docs.
I´m trying to build my first connection between a React component to Redux to gather data from my node API.
This is a simple component for now, but it will grow in the future and will derive subcomponents that will allow me to build a full User CRUD interface (list, edit, delete, view, etc.). In that sense, I need to connect the action functions to the object this.props so that it can be inheritated by the child components.
Here is my code:
Component UserGrid - A table data grid that will load users information
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as userActions from '../../actions/userActions';
class UserGrid extends React.Component {
componentWillMount() {
this.props.fetchUsers();
}
render() {
const mappedUsers = users.map(user => <li>{user.email}</li>);
return (
<div>
<ul>{mappedUsers}</ul>
</div>
);
}
}
function mapStateToProps(state) {
return {
users: state.users
}
}
export default connect(
mapStateToProps,
bindActionCreators(userActions, dispatch)
)(UserGrid);
My userAction, that effectively will load users from an AJAX call:
import axios from "axios";
export function fetchUsers() {
return function(dispatch) {
axios.get("/api/users")
.then((response) => {
dispatch({type: "FETCH_USERS_FULFILLED", payload: response.data});
})
.catch((err) => {
dispatch({type: "FETCH_USERS_REJECTED", payload: err});
})
}
}
With this code I´m getting the following error:
Uncaught ReferenceError: dispatch is not defined
at Object.<anonymous> (bundle.js:37984)
at __webpack_require__ (bundle.js:556)
at fn (bundle.js:87)
at Object.<anonymous> (bundle.js:37711)
at __webpack_require__ (bundle.js:556)
at fn (bundle.js:87)
at Object.<anonymous> (bundle.js:8466)
at __webpack_require__ (bundle.js:556)
at fn (bundle.js:87)
at Object.<anonymous> (bundle.js:588)
(anonymous) # bundle.js:37984
__webpack_require__ # bundle.js:556
fn # bundle.js:87
(anonymous) # bundle.js:37711
__webpack_require__ # bundle.js:556
fn # bundle.js:87
(anonymous) # bundle.js:8466
__webpack_require__ # bundle.js:556
fn # bundle.js:87
(anonymous) # bundle.js:588
__webpack_require__ # bundle.js:556
(anonymous) # bundle.js:579
(anonymous) # bundle.js:582
What is the correct way to connect my component to the Redux services created?
In the component you wish to connect you need to define the function mapDispatchToProps. This function will take dispatch as a parameter, and will receive this parameter when connect calls the function.
Here is some example code pulled from one of my recent projects.
function mapDispatchToProps(dispatch) {
return {
adminActions: bindActionCreators(adminOrdersActions, dispatch),
schoolActions: bindActionCreators(schoolOrdersListActions, dispatch),
userActions: bindActionCreators(userActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AllOrders);
Now dispatch is defined.
EDIT: To clarify, doing this will now give you access to your actions with the following syntax. this.props.actions.yourAction, or whatever you called the actions in the mapDispatchToProps.
This is your code with my changes:
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as userActions from '../../actions/userActions';
class UserGrid extends React.Component {
componentWillMount() {
console.log(JSON.stringify(this.props));
//this.props.fetchUsers();
this.props.actions.fetchUsers();
}
render() {
const mappedUsers = users.map(user => <li>{user.email}</li>)
return (
<div>
<ul>{mappedUsers}</ul>
</div>
)
}
}
function mapStateToProps(state) {
return {
users: state.users
}
}
function mapDispatchToProps(dispatch) {
// this function will now give you access to all your useractions by simply calling this.props.actions.
//if the key of this object would not be actions, but rather foobar, you will get your actions by
// calling this.props.foobar
return {
actions: bindActionCreators(userActions, dispatch)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserGrid);
I don't think you want to use bindActionCreators here. Here's what the docs say (emphasis mine):
Normally you should just call dispatch directly on your Store instance. If you use Redux with React, react-redux will provide you with the dispatch function so you can call it directly, too.
The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it.
Since that's not what you're doing, you should instead call dispatch directly. With react-redux, connect will inject it into your props, so you can just do this:
componentWillMount() {
this.props.dispatch(fetchUsers());
}
As Jordan said I would not use bindActionCreators.
Your component should look something like this:
import React from 'react';
import { connect } from 'react-redux';
import myAction from './my-action';
class MyComponent extends React.Component {
componentDidMount() {
this.props.myAction();
}
render() {
return "Hi!"
}
}
const mapStateToProps = (state) => ({
myState: state.myState
});
const mapDispatchToProps = (dispatch) => ({
myAction: () => dispatch(myAction())
});
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);