React with Redux - unable to bind action to parent - reactjs

I am new to the Redux pattern i'm having some trouble linking an action in a separate JS file to it's parent component. Here is the component:
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import playSample from './sampleActions/clickToPlay';
class SamplesInnerLrg extends Component {
render() {
return <div>
{
this.props.samples.map((sample) => {
return (
<div key={sample.id} className="sample-comp-lge">
<div className="sample-comp-lge-header">
<span className="sample-comp-lge-Name">{sample.sampleName}</span>
<span className="sample-comp-lge-id">{sample.sampleFamily}</span>
</div>
<div className="sample-comp-lge-audio" ref={sample.id} onClick={() => this.bind.playSample(sample)}>
<audio preload="auto" id="myAudio">
<source src={sample.soundSource} type="audio/wav" />
</audio>
</div>
<div className="sample-comp-lge-owner">{sample.uploader}</div>
</div>
)
})
}
</div>
}
}
function mapStateToProps(state) {
return {
samples:state.samples
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({playSample:playSample},dispatch)
}
export default connect(mapStateToProps,matchDispatchToProps)(SamplesInnerLrg);
Specifically I am trying to have an onClick action on this line that will call a function in an imported file (clickToPlay.js):
<div className="sample-comp-lge-audio" ref={sample.id} onClick={() => this.bind.playSample(sample)}>
The clickToPlay file looks like so:
import $ from 'jquery';
export const playSample = (sample) => {
console.log(sample);
return {
type:"Play_Sample_clicked",
payload:sample
}
};
the error i'm getting on click is Cannot read property 'playSample' of undefined. I'm guessing I have bound the action to the component correcly but I can't tell why?
EDIT:
Here is my index.js file as requested:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import { createStore,compose } from 'redux';
import allReducers from './reducers';
const store = createStore(allReducers,compose(
window.devToolsExtension ? window.devToolsExtension() : f => f
));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
,
document.getElementById('root')
);

You aren't exporting 'playSample' as the default export, you have two ways to reslove this:
You can do:
import { playSample } from './sampleActions/clickToPlay';
or
you can change export const playSample to const playSample Then add export default playSample at the end of your file.
Another note I want to mention about this line:
return bindActionCreators({playSample:playSample},dispatch)
I don't see why you are doing {playSample:playSample} just change it to playSample. ES6 allows you to eliminate key if it's the same as value, this is called object literal property value shorthand.

Related

Trying to render hook Statement, but its not getting render

i'm trying to render a useHook statement in React that just display the length of the array and nothing getting render.
Here is APP.js
import React, { useState } from 'react'
import TodoList from './TodoList'
function App() {
const [todos, setTodos] = useState(['test1', 'test2'])
return (
<>
<TodoList todos={todos} />
<input type="text" />
<button>Add Todo</button>
<button>Clear Completed Todos</button>
<div>0 left to do</div>
</>
)
}
export default App;
Here TodoList.js
import React from 'react'
export default function TodoList(todos) {
return (
<div>
{todos.length}
</div>
)
}
Here index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Screenshot of what getting render
screenshot
Change the TodoList Component to this,
import React from 'react'
export default function TodoList({todos}) {
return
<div>
{todos.length}
</div>
)
or
import React from 'react'
export default function TodoList(props) {
return (
<div>
{props.todos.length}
</div>
)
Just remember you receive props in the form of an object, so you can either de-structure it or use dot notation or bracket notation to access the peops you pass to a component

default is not a function React Type error

Hi guys i want to make speech to text in React component. But when i run it I get this error:
react_speech_recognition__WEBPACK_IMPORTED_MODULE_1___default(...) is not a function
Can someone show me what to do?
import React, { Component } from 'react'
import SpeechRecognition from 'react-speech-recognition'
class Mic extends Component {
render() {
const { transcript, resetTranscript, browserSupportsSpeechRecognition } = this.props
if (!browserSupportsSpeechRecognition) {
return null
}
return (
<div>
<button onClick={SpeechRecognition.startListening}>Start</button>
<button onClick={SpeechRecognition.stopListening}>Stop</button>
<button onClick={resetTranscript}>Reset</button>
<p>{transcript}</p>
</div>
)
}
}
export default SpeechRecognition(Mic)
In app.js i run it like this (if this is necessary):
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Container from './components/container/Container';
import Database from './components/database/Database';
import Mic from './components/mic/Mic';
import Test from './components/test/Test';
function App() {
return (
<Mic/>
//<Test/>
);
}
export default App;
It is because of this line SpeechRecognition(Mic) . The Error states that the default export from your module is not a function which means that SpeechRecognition is not a function so you cannot call it .
change your code as
import React from 'react'
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'
const Mic = () => {
const { transcript, resetTranscript } = useSpeechRecognition()
if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
return null
}
return (
<div>
<button onClick={SpeechRecognition.startListening}>Start</button>
<button onClick={SpeechRecognition.stopListening}>Stop</button>
<button onClick={resetTranscript}>Reset</button>
<p>{transcript}</p>
</div>
)
}
export default Mic
Looks like you have installed the latest version, but trying to use it in old way.
Please take a look at this Migration Guide

Fetching data in other components with react hook

Im new to react hooks and are experimenting a bit. I can display my values that are generated in Provider.js in App.js through Comptest.js. My problem is that the structure of my project with css etc makes it inconvenient to have a structure in the App.js like this:
<Provider>
<Comptest />
</Provider>
is it possible to fetch the data without displaying the components in that way in the app? just passing it between the components.
Here is a compact version of my application:
App.js
import React, { useContext } from "react";
import Provider from "./Provider";
import Comptest from "./Comptest";
import DataContext from "./Context";
function App() {
return (
<div className="App">
<h2>My array!</h2>
<Provider>
<Comptest />
</Provider>
</div>
);
}
export default App;
Provider.js
import React, { useState } from "react";
import DataContext from "./Context";
const Provider = props => {
const data = ["item1", "item2"];
return (
<DataContext.Provider value={data}>{props.children}</DataContext.Provider>
);
};
export default Provider;
Comptest.js
import React from "react";
import DataContext from "./Context";
const Comptest = () => {
const content = React.useContext(DataContext);
console.log(content);
return <div>{(content)}</div>;
};
export default Comptest;
Context.js
import React from "react";
const DataContext = React.createContext([]);
export default DataContext;

Getting undefined when accessing redux stores state property in react App

I am using redux in my react app and I am getting undefined when I access redux state property in one of my component, why is that? the state is valid when I call console.log in reducer file : here is my reducerFile :
const initState = {
isCurrentUser : true
}
export default function(state=initState, action) {
console.log(`this is from localAuthReducer ${state.isCurrentUser}`)
switch(action.type) {
default:
return state
}
}
Here is my react component :
import React, {Component} from 'react';
import styles from './IndexPage.module.scss';
import { connect } from 'react-redux';
import Header from './../../components/Header/Header';
class IndexPage extends Component {
render() {
return(
<div className={styles.container}>
<Header
isCurrentUser = {this.props.isCurrentUser}
/>
{ console.log(`this is from indexPage ${this.props.isCurrentUser}`)}
</div>
);
}
}
function mapStateToProps(state) {
return {
isCurrentUser : state.isCurrentUser
}
}
export default connect(mapStateToProps, null)(IndexPage);
Here is my index.js file :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/App';
import {Provider } from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import reducers from './reducers/index';
import reduxThunk from 'redux-thunk';
const store = createStore(
reducers,
applyMiddleware(reduxThunk)
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.querySelector("#root"));
I dont know where I am going wrong isCurrentUser must have value of true as it is the default value of the redux state

React + Redux: Cannot read property 'props' of null error

I have been receiving a Cannot read property 'props' of null error in th client app that I am currently building with react and redux.
I have been trying to implement a wrapper component/container for other react components in a web app as follows.(The reason I have included the contents of 4 files is that I don't know where the error is originating from)
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import store, {history} from './App/store';
import Init from './App/Init';
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Router path="/" component={Init}>
<IndexRoute component={Container}/>
<Route path="/view/:ItemId" component={Single}></Route>
</Router>
</Router>
</Provider>,
document.getElementById('main')
);
class Container extends Component{
render(){
return(
<div>hello</div>
);
}
}
class Single extends Component{
render(){
return(
<div>hello</div>
);
}
}
Init.js
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import * as actionCreators from './ActionCreators'
import App from './App';
function mapStateToProps(state, ownProps){
return{
items: state.items,
entities: state.entities,
};
}
function mapDispatchToProps(dispatch){
return bindActionCreators(actionCreators, dispatch);
}
const Init = connect(mapStateToProps, mapDispatchToProps)(App);
export default Init;
store.js
import { createStore, compse, applyMiddleware } from 'redux';
import { browserHistory } from 'react-router';
import thunkMiddleware from 'redux-thunk';
import {syncHistoryWithStore} from 'react-router-redux';
//import the root reducer
import rootReducer from './rootReducer';
//import data
import {entities} from '../../data/entities';
import {items} from '../../data/items';
//create an object for the default data
const defaultState = {
items,
entities,
};
const store = createStore(rootReducer, defaultState);
export const history = syncHistoryWithStore(browserHistory, store);
export default store;
and App.js
import React, {Component} from 'react';
export default class App extends Component {
render(){
return(
<div>
<div className="content-wrapper">
<div className="grid-page">
{React.cloneElement({...this.props}.children, {...this.props})}//The error occurs here
</div>
</div>
</div>
);
}
}
and here is the console log of the error
ReactElement.js:271 Uncaught TypeError: Cannot read property 'props' of null
at Object.ReactElement.cloneElement (ReactElement.js:271)
at Object.cloneElement (ReactElementValidator.js:223)
at App.render (App.js:15)
at App.<anonymous> (makeAssimilatePrototype.js:15)
at ReactCompositeComponent.js:796
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
Please excuse the lack of brevity in my question, I have not found any answers on stack overflow that address the issue I am having, but if you could shed some light on what is going wrong, that would be great.
Thanks
class definitions in the spec don't get hoisted, though Babel is compiling it down to a function expression, which will hoist the variable, which is why the code doesn't crash at runtime, but the class definitions are still undefined
putting your class Container and class Single above your call to ReactDOM.render should solve this issue.

Resources