I'm connecting store to my react application, But it gives me error TypeError: state is undefined
store/index.js(Creating Reducer function)
import {createStore} from 'redux';
const counterReducer = (state:{counter:0},action) => {
if(action.type==='increment')
{
return {
counter: state.counter + 1
}
}
if (action.type === 'decrement') {
return {
counter: state.counter - 1
}
}
return state;
}
const store = createStore(counterReducer);
export default store;
main index.js(Main index of my file)
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './store/index';
import './index.css';
import App from './App';
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
Now I'm using my Counter components like this:(src/components/Counter.js)
import classes from './Counter.module.css';
import {useSelector} from 'react-redux';
const Counter = () => {
const counter = useSelector(state => state.counter);
const toggleCounterHandler = () => {};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
<div className={classes.value}>{counter}</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
here is my package.json:
{
"name": "redux-basics",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.9",
"#testing-library/react": "^11.2.5",
"#testing-library/user-event": "^12.6.3",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-redux": "^7.2.4",
"react-scripts": "4.0.2",
"redux": "^4.1.0",
"web-vitals": "^1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Error:
TypeError: state is undefined
Counter/counter<
C:/Users/nikku/Desktop/redux-project/src/components/Counter.js:6
3 |
4 |
5 | const Counter = () => {
> 6 | const counter = useSelector((state) => state.counter);
7 | const toggleCounterHandler = () => {};
8 |
9 | return (
useSelector should get state as argument by default right? but here it is saying it is undefined. Ca you please share you thoughts? Did I do something wrong ?
In order to initialize a default state, you need to use the = assignment operator
const counterReducer = (state = {counter:0},action) => {
Default state is initialized like this. This will fix your issue.
function appReducer(state = MyInitialState, action) {
switch (action.type) {
case "my_custom_type":
return {
...state
};
default:
return state;
}
}
Related
I want to fetch my data from port 8000,but it still get error 404.
Because it uses port 3000 ,I set proxy in package.json.
I don't know the reason why it goes wrong.
Error below:
GET http://localhost:3000/hotels/countByCity?cities=berlin,madrid,lodon 404 (Not Found)
Here are my relative codes:
pacakge.json
{
"name": "booking",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/free-regular-svg-icons": "^6.2.0",
"#fortawesome/free-solid-svg-icons": "^6.2.0",
"#fortawesome/react-fontawesome": "^0.2.0",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.1.3",
"date-fns": "^2.29.3",
"react": "^18.2.0",
"react-date-range": "^1.4.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy":"http://localhost:8000/api"
}
useFetch.js
import { useEffect, useState } from "react";
import axios from "axios";
const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const res = await axios.get(url);
setData(res.data);
} catch (err) {
setError(err);
}
setLoading(false);
};
fetchData();
}, [url]);
const reFetch = async () => {
setLoading(true);
try {
const res = await axios.get(url);
setData(res.data);
} catch (err) {
setError(err);
}
setLoading(false);
};
return { data, loading, error, reFetch };
};
export default useFetch;
featured.jsx
import React from 'react'
import "./featured.css"
import useFetch from "../../hooks/useFetch"
const Featured = () => {
const{ data,loading,error}=useFetch("/hotels/countByCity?cities=berlin,madrid,lodon")
console.log(data);
return (
<div className='featured'>
<div className="featuredItem">
<img className='featuredImg' src="https://i.pinimg.com/564x/53/47/6a/53476a9ce987dcc41b19385744f09ab3.jpg" />
<div className="featureTitle">
<h1>AmazĂ´nia.</h1>
<h3>189 properties</h3>
</div>
</div>
<div className="featuredItem">
<img className='featuredImg' src="https://i.pinimg.com/564x/cf/fb/34/cffb34899bc7e9262f4f91270d51677d.jpg" />
<div className="featureTitle">
<h1>Avignon’s historic center.</h1>
<h3>259 properties</h3>
</div>
</div>
<div className="featuredItem">
<img className='featuredImg' src="https://i.pinimg.com/564x/7f/6f/0a/7f6f0a8668aa2da61d9025859406e2f1.jpg" />
<div className="featureTitle">
<h1>Naz City Hotel Taksim</h1>
<h3>345 properties</h3>
</div>
</div>
</div>
)
}
export default Featured
I am using the following packages and have installed tailwindcss in the following project folder /home/admin/Desktop/Code/main_project/client/package.json:
{
"name": "react-app",
"version": "1.0",
"private": true,
"dependencies": {
"babel-eslint": "10.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router": "^6.3.0",
"react-scripts": "3.2.0",
"redux": "^4.1.1",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.0.1",
"web3": "^1.6.1",
"web3-eth-contract": "^1.5.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"tailwindcss": "^3.0.24"
}
}
My tailwind.config.js looks like the following:
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
As you can see my react-project lies in a subfolder.
My postcss.config.js looks like the following:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
This is my index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
In my index.js I am loading my index.css:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from "./redux/store";
import { Provider } from "react-redux";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
My App.js looks like the following:
import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "./redux/blockchain/blockchainActions";
import { fetchData } from "./redux/data/dataActions";
import "./App.css";
function App() {
const dispatch = useDispatch();
const blockchain = useSelector((state) => state.blockchain);
const data = useSelector((state) => state.data);
const [CONFIG, SET_CONFIG] = useState({
CONTRACT_ADDRESS: "",
SCAN_LINK: "",
NETWORK: {
NAME: "",
SYMBOL: "",
ID: 0,
},
NFT_NAME: "",
SYMBOL: "",
MAX_SUPPLY: 1,
WEI_COST: 0,
DISPLAY_COST: 0,
GAS_LIMIT: 0,
MARKETPLACE: "",
MARKETPLACE_LINK: "",
SHOW_BACKGROUND: false,
});
const getData = () => {
if (blockchain.account !== "" && blockchain.smartContract !== null) {
dispatch(fetchData(blockchain.account));
}
};
const getConfig = async () => {
const configResponse = await fetch("/config/config.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const config = await configResponse.json();
SET_CONFIG(config);
};
useEffect(() => {
getConfig();
}, []);
useEffect(() => {
getData();
}, [blockchain.account]);
return (
<>
<h1 className="text-3xl font-bold underline">Welcome</h1>
<>
);
}
export default App;
However, the components in my App.js do not get rendered with tailwindcss.
Any suggestions what I am doing wrong?
I appreciate your replies!
My firebase has some problems which the console says firestore is undefined. I think the problem actually comes from my firebaseApp or somewhere but i don't know how to fix it. it'd be kind of you guys to help me! Thank you so much!
This is my firebase.js:
import firebase from 'firebase';
const firebaseApp = firebase.initializeApp[{
apiKey: "<API_KEI>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
projectId: "<PROJECT_ID>",
storageBucket: "<PROJECT_ID>.appspot.com",
messagingSenderId: "<SENDER_ID>",
appId: "<APP_ID>",
measurementId: "<MESURMENT_ID>"
}];
const db = firebaseApp.firestore();
const auth = firebase.auth();
export {
auth,
db
};
This is my SignIn.js:
import React from "react";
import firebase from "firebase";
import {
auth
} from "../firebase.js";
function SignIn() {
function signInWithGoogle() {
const provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider);
}
return ( <
div >
<
button onClick = {
signInWithGoogle
} > Sign in with google < /button>{" "} <
/div>
);
}
This is my App.js:
import React from 'react'
import SignIn from './components/SignIn'
import Chat from './components/Chat'
function App() {
return ( <
div >
<
SignIn / >
<
Chat / >
<
/div>
)
}
export default App
This is my package.json:
{
"name": "image-search",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.4.1",
"#emotion/styled": "^11.3.0",
"#fortawesome/fontawesome-free": "^5.15.4",
"#material-ui/core": "^4.12.3",
"#material-ui/icons": "^4.11.2",
"#mui/icons-material": "^5.0.1",
"#mui/material": "^5.0.1",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"firebase": "^8.10.0",
"font-awesome": "^4.7.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-firebase-hooks": "^3.0.4",
"react-scripts": "4.0.3",
"uuidv4": "^6.2.12",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/preset-react": "^7.14.5"
}
}
You can use latest firebase and check the docs below.
In your code, const db = firebaseApp.firestore();, but latest version use const db = getFirestore(app); to initialize db.
This is a demo from official network.
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
// Follow this pattern to import other Firebase services
// import { } from 'firebase/<service>';
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
//...
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// Get a list of cities from your database
async function getCities(db) {
const citiesCol = collection(db, 'cities');
const citySnapshot = await getDocs(citiesCol);
const cityList = citySnapshot.docs.map(doc => doc.data());
return cityList;
}
And find more information in this page firebase
i want to use all eventHandler of redux-form as show in sameple output image but its not coming as a props so i facing undefine error now what i can do to solve the issue
i have imported reducers in index.js file of src folder and create store
package.json
{
"name": "reactjs",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^4.11.0",
"#material-ui/icons": "^4.9.1",
"prop-types": "^15.7.2",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.2.0",
"react-transition-group": "^4.4.1",
"redux-form": "^8.3.6"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
}
reducers/index.js
import { reducer } from 'redux-form';
import { combineReducers } from "redux";
export default combineReducers({
reducer
})
TouristRegistration.js
import React, { Component } from 'react';
import { reduxForm, Field } from "redux-form";
import { Button } from "#material-ui/core"
import RegistrationField from "./ReaperComponent"
class TutiorsRegistrationForm extends Component {
handlenextpage = () => {
this.props.nextPage()
}
render() {
return (
<form>
<Field
type="text"
name="FirstName"
component={RegistrationField}
/>
<Button
color="primary"
variant="contained"
type="submit"
>Next
</Button>
</form>
);
}
}
const validate = (value) => {
const errors = {}
if (!value.FirstName) {
errors.FirstName = "Required"
}
console.log("error " + JSON.stringify(errors));
return errors;
}
export default reduxForm({
validate: validate,
form: 'TutiorsRegistrationForm'
})(TutiorsRegistrationForm);
RegistrationField.js
import React from 'react';
import { TextField } from "#material-ui/core"
const ReaperComponent = (props) => {
console.log("props " + JSON.stringify(props));
return (
<TextField />
);
}
export default ReaperComponent;
output
of instructor
output in my case
props {"input":{"name":"FirstName","value":""},"meta":{"active":false,"asyncValidating":false,"autofilled":false,"dirty":false,"form":"TutiorsRegistrationForm","invalid":false,"pristine":true,"submitting":false,"submitFailed":false,"touched":false,"valid":true,"visited":false}}
I am following this tutorial on React-Redux and I stumbled upon error on 1st part of section "React Redux tutorial: asynchronous actions in Redux, the naive way".
Post.componentDidMount
src/js/components/Posts.js:12
9 |
10 | componentDidMount() {
11 | // calling the new action creator
> 12 | this.props.getData();
| ^ 13 | }
14 |
15 | render() {
My understanding is that props from store is not passed down from the App component to Posts component. I have repeated the steps several times but I still cannot see the exact culprit. The source code from Git works just fine. I noticed, there are difference between my local and that of the GIT repo.
This is my package.json
{
"name": "react-redux-study",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"react-redux": "^7.2.0",
"redux": "^4.0.5"
}
}
And this is the package.json from the Git repo.
UPDATE: Added my App.js and Posts.js
App.js
import React from "react";
import List from "./List";
import Form from "./Form";
import { Post } from "./Posts";
const App = () => (
<>
<div>
<h2>Articles</h2>
<List />
</div>
<div>
<h2>Add a new article</h2>
<Form />
</div>
<div>
<h2>API posts</h2>
<Post />
</div>
</>
);
export default App;
Posts.js
import React, { Component } from "react";
import { connect } from "react-redux";
import { getData } from "../actions/index";
export class Post extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// calling the new action creator
this.props.getData();
}
render() {
return null;
}
}
export default connect(
null,
{ getData }
)(Post);
I can actually just move on and use the source code from Git but I do want to understand what is the exact issue.
Issue :
// posts.js
export class Post extends Component { // <---- First : Export
...
}
export default connect( // <----- Second : Export
null,
{ getData }
)(Post);
// inside app.js
// you are importing first import, not the default which is connecting to you store
import { Post } from "./Posts";
Solution :
Change this line
import { Post } from "./Posts";
To
// import the default one
import Post from "./Posts";
In app component
<Post getData={postdata} />
In Posts component you can get data like this.
componentDidMount() {
let posts=this.props.getData;
}