Home > Blockchain >  How to pass data by button click in redux react js
How to pass data by button click in redux react js

Time:05-17

I'm new to redux. I have three components are TextField , Button and View. I just stored textfield data in redux configureStore, How to pass data by button click from button component to view component. Im using context how to change in redux.

Codesandbox link using redux

Here I tired but I want to diplay only when button click.

CodeSanbox Link using Context

CodePudding user response:

Your reducer has the following structure:

initialState: { value: { text: "" } }

But you are triggering an action like this:

dispatch(updateValue("youy text here"));

When it should be like this:

dispatch(updateValue({ text: "your text here" }));

CodePudding user response:

Here is the solution I make ready for you

App.js

import React, { useEffect, useState } from "react";
import "./styles.css";
import TFPage from "./TFPage";
import BtnPage from "./BtnPage";
import ViewPage from "./ViewPage";
import { useSelector, useDispatch } from "react-redux";
import { updateValue } from "./features/Updater";

export default function App() {
  const myData = useSelector((state) => state.update.value);
  const [myTxt, setMyTxt] = useState(myData.text);

  const dispatch = useDispatch();
  const handleUpdate = () => {
    console.log(myData);
    dispatch(updateValue(myTxt));
  };

  return (
    <div className="App">
      <TFPage setMyTxt={setMyTxt} myTxt={myTxt} />
      <BtnPage handleUpdate={handleUpdate} />
      <ViewPage />
    </div>
  );
}

BtnPage.js

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { updateValue } from "./features/Updater";

export default function BtnPage({handleUpdate}) {

  return (
    <div>
      <button onClick={() => handleUpdate()}> Update </button>
    </div>
  );
}

TFPage.js

import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { updateValue } from "./features/Updater";

export default function TFPage({myTxt, setMyTxt}) {
  //const myData = useSelector((state) => state.update.value);

 // const [myTxt, setMyTxt] = useState(myData.text);

  //const dispatch = useDispatch();

  const handleChange = (char) => {
    setMyTxt(char);
    //dispatch(updateValue(myTxt));
  };

  // useEffect(() => {
  //   // console.log('useEff - render');
  //   dispatch(updateValue({ text: myTxt }));
  // }, [myTxt]);

  return (
    <div>
      <input
        value={myTxt}
        placeholder="Enter Some Text"
        onChange={(e) => handleChange(e.target.value)}
      />
    </div>
  );
}

ViewPage.js

import React from "react";
import { useSelector } from "react-redux";

export default function ViewPage() {
  const myData = useSelector((state) => state.update.value);
  console.log(myData);
  return (
    <div>
      <h1> {myData} </h1>
    </div>
  );
}
  • Related