javier cruz
javier cruz

Reputation: 23

How to send data between components redux/react

I'm trying to learn redux and react, I'm trying to create CRUD app, so far I made Insert/Delete, I also did update logic but I'm struggling on how to send data from one row in my table (when clicking button 'Editar') to my form on the left side. Each side is a different component, the simplest way I thought was using getElementById and fill the fields but when doing this react takes it as a blank input when I try to save. The other option was using redux creating a getId action and call it from my 'Editar' button but don't know how to send data to my other container after executing the action.

Any hint would be helpful.

My Application My Application

Upvotes: 1

Views: 3441

Answers (2)

Afzal Hossain
Afzal Hossain

Reputation: 3338

install react-redux and use the connect function from that. Example:

import React, {Component} from 'react';
import {connect} from 'react-redux';

class ExampleComponent extends Component {
    render() {

        const something = this.props.something; // in case you need to read part of the redux state

        const mydata='something'; // data from this component

        return (
            <div>
                <button onClick={()=>{this.props.sendData({data: mydata})}}>Send Data</button>
            </div>
        );
    }
}


// map state
function mapStateToProps(state) {
    return {
        something: state.something
    }
}

// map dispatch
function mapDispatchToProps(dispatch) {
    return {
        sendData: (data) => {
            dispatch({type:'SOME_TYPE_FOR_REDUCER', payload:data})
        }
    }
}

// connect and export
export default connect(mapStateToProps, mapDispatchToProps)(ExampleComponent);

Upvotes: 2

Gokul Chandrasekaran
Gokul Chandrasekaran

Reputation: 545

You could create a state in your app state that contains the selected item to be edited. The editor component cab be subscribed to that state. When you click Editar button it triggers an action EDIT_ITEM which will populate the redux state with the item to edited.

Clicking the Ok button will update the redux state for the items.

// State 
    const state = {
    items: [],
    selected: {}
}

    //Actions
    const EDIT_ITEM = 'edit'
    const UPDATE_ITEM = 'edit'
    //Reducers
    const reducer = (state, action) {
        switch({action, data})  {
            EDIT_ITEM: 
                return Object.assign({}, state, data)
            SAVE_ITEM: 
                //save based on id
        }
}

Upvotes: 0

Related Questions