Passing Value From Callback In Component To Another Component

- 1 answer

I am using giphy-api module from nodejs and I want to pass this data to react.

I have two components:

Api.js is the one that successfully connects with node.js and returns a callback with all the API data. App.js is the main component. I import Api.js and when I console.log this callback message it works. I tried props and states but because the Api.js returns a Callback I don't know how to consume it.


import openSocket from "";
const socket = openSocket("http://localhost:5000/");

function connect(cb) {
  // listen for any messages coming through
  // of type 'chat' and then trigger the
  // callback function with said message
  socket.on("chat", message => {
    // trigger the callback passed in when
    // our App component calls connect

export { connect };

App.js :

import React from 'react';
import { connect } from './api';
import './App.css';

class App extends React.Component {
  constructor(props) {
    // call our connect function and define
    // an anonymous callback function that`
    // simply console.log's the received
    // message
    var gifs = connect(message => {
    this.state = {
            books: [
                    name: 'Zero to one',
                    isbn: '9780804139298',
                    author: 'Peter Thiel',
                    cover: '',
                    status: false
      gipphy: gifs

  render () {

      return (
        <div className=".App-logo">
            <li className=".App-logo">
              <img src={ this.state.books[0].cover} alt=" animations"/>
              <img src={ this.state.gifs[0].images.original.url} alt=" animations"/>

export default App;

TypeError: Cannot read property 'gipphy' of null

Now the console.log is undefined



I think the issue is because, you have stored gifs value in gipphy state variable. So instead of this.state.gifs you should use this.state.gipphy,

<img src={ this.state.gipphy[0].images.original.url} alt=" animations"/>

Also make sure gifs contains correct value. Simply make a console.log(gifs) in a constructor. If you don't get gifs value, then I think you need to return it from callback,

var gifs = connect(message => {
   return message;   //return the message here


I think your API is taking time to return data. You can make use of componentDidMount method,

   connect(message => {
          gipphy: message

You need to conditionally render your img,

{this.state.giphy && this.state.giphy.length > 0 && <img src={ this.state.giphy[0].images.original.url} alt=" animations"/>}