[Ethereum] Updating a struct value in mapping

mappingsoliditystruct

I am trying to update a value in a struct that is mapped. I tried updating a value in the smart contract, it asked me to confirm the transaction but when I check the value it doesn't seem to change please help as I'm new to solidity
My smart contract


contract Project {
    string public name;
    uint public postCount = 0;
    uint public docCount = 0;

    mapping(uint => Doc) public Docs;

    struct Doc {
        uint id;
        string title;
        string content;
        address author;
    }

    event DocCreated(
        uint doc_id,
        string title,
        string content,
        address author
    );

    event DocUploaded(
        uint doc_id,
        string title,
        string content,
        address author
    );

    constructor() public  {
        name="project";
    }

    function uploadDoc(string memory _IPFShash, string memory _title) public {
        //upload documents to IPFS get hash then save hash on to blockchain
        docCount++;
        //make a doc
        Docs[docCount] = Doc(docCount, _title, _IPFShash, msg.sender);

        //Trigger Event, solidty provides a way for users to track events and test
        emit DocCreated(docCount, _title, _IPFShash, msg.sender);
    }



    function updateDoc(uint _id, string memory _IPFShash, string memory _title) public {

        for (uint i = 0; i <= docCount; i++) {
            if(Docs[i].id == _id){
                Docs[i].content  = _IPFShash;
            }

        //Trigger Event, solidty provides a way for users to track events 
        emit DocUploaded(_id,  _title, _IPFShash, msg.sender);
        }

    }

}
************************************************************************************
//im calling this with this react script
    updateDoc(id, content, title) {
        this.setState({ loading: true })
        this.state.project.methods.updateDoc(id, content, title).send({ from: this.state.account })
            .on('receipt', (receipt) => {
                console.log('loaded')
            })
        window.location.reload()
    }


Best Answer

I tried the contracts in Remix and they kind of work, updateDoc might trigger the event DocUploaded multiple times and the _title is not updated.

The function updateDoc doesn't need to iterate over the mapping. It can access the Doc directly with _id.

function updateDoc(uint _id, string memory _IPFShash, string memory _title) public {
    if (Docs[_id].id == _id) {
        Docs[_id].content  = _IPFShash;

        //Trigger Event, solidty provides a way for users to track events 
        emit DocUploaded(_id,  _title, _IPFShash, msg.sender);
    }
}

The problem might be that your transaction isn't mined immediately so the changes will not reflect on your dapp when it is reloaded. A common solution is to show a progress bar until the transactions is confirmed.

Related Topic