mobxjs / mobx-utils

Utility functions and common patterns for MobX
MIT License
1.18k stars 125 forks source link

Question about the second value in fromPromise function (optional value) #280

Open tzipisheinin opened 3 years ago

tzipisheinin commented 3 years ago

I'm sending the same promise that I'm fetching the data into (exactly as the example). I excepted to not see the pending state at all (some loading I have on pending state). but I still can see it - passing very quick, but exist. Why?

tzipisheinin commented 3 years ago

Can someone please help with that?

mweststrate commented 3 years ago

Building a small code sandbox demonstrating your problem typically helps

tzipisheinin commented 3 years ago

You absolutely right. Thanks for answering. I made an example now, but the strange thing is that in this small example it's stucked on the pending level every time I send the optional value to the fromPromise function. (if I send only request it does work)

Could be I'm using old version? My mobx versions are :

"mobx": "^5.0.2", "mobx-react": "^5.2.3", "mobx-utils": "^5.1.0",

The store

class Results {

   @observable searchLoader;

   constructor() {
      this.search();
   }

   @action
   search = () => {
      this.searchLoader = fromPromise(
         window.fetch("https://audyx-alpha.s3-eu-west-1.amazonaws.com/fond.jpg"),
         this.searchLoader
      )
   }

   @computed
   get imageSrc() {
      if (this.searchLoader && this.searchLoader.value) {
         return this.searchLoader.value.url;
      }
   }
}

const result = new Results();
export default result;

The Components

@inject('appStore')
@observer
class Image extends React.Component {

   constructor(props) {
      super(props);
      props.appStore.example.search();
   }

   render() {
      const { imageSrc, searchLoader } = this.props.appStore.example;
      return (
         <AsyncRender promise={searchLoader}>
            <img alt="audyx" src={imageSrc}></img>
         </AsyncRender>
      )
   }
}

const Example = () => {
   const [showData, setShowData] = useState(false);

   return (
      <React.Fragment>
         <button onClick={() => setShowData(!showData)}>click to toggle</button>
         {showData ?
            <Image /> : <div>Nothing!</div>}
      </React.Fragment>
   )
}