GithubHelp home page GithubHelp logo

timolins / react-hot-toast Goto Github PK

View Code? Open in Web Editor NEW
9.1K 9.1K 301.0 1.86 MB

Smoking Hot React Notifications ๐Ÿ”ฅ

Home Page: https://react-hot-toast.com

License: MIT License

TypeScript 65.64% JavaScript 5.71% CSS 3.26% MDX 25.39%
notifications react snackbar toast-notifications

react-hot-toast's Introduction

Follow @timolins on Twitter

react-hot-toast's People

Contributors

anishde12020 avatar benjenkinson avatar casperiv0 avatar cbserra avatar cristianbote avatar d-32 avatar diksown avatar domenicrosati avatar eeston avatar gr-qft avatar hudochenkov avatar jlalmes avatar karlshea avatar kilian avatar luccasoli avatar mafzal91 avatar pipboy3000 avatar ruisaraiva19 avatar silvenon avatar stivaugoin avatar takeshikriang avatar timolins avatar timurmaio avatar tmcw avatar yj-ang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-hot-toast's Issues

Unwanted peer dependency message

When installing react-hot-toast (or running npm install in a project that already has react-hot-toast) the following warning is shown:

npm WARN [email protected] requires a peer of csstype@^2.6.2 but none is installed. You must install peer dependencies yourself.

Documentation says nothing about need of csstype.

Maybe react-hot-toast should make it regular dependency if it's needed?

On the other note, there are users, who are using just headless mode, and they don't need neither goober or csstype.

Loading toast is removed before resolving the promise.

I noticed a weird behavior when running a promise that takes fairly long (about 30s) the loading toast is automatically dismissed even before resolving the promise, when it's resolved the success toast appears.

Can you reproduce this? Try having a promise that takes about 30 or 40 seconds to execute.

toast.promise(subtitlesPromise, {
  loading: 'Generating your subtitles, please wait...',
  success: 'Subtitles generated!',
  error: 'Error generating subtitles.',
});

Thanks Timo for this awesome library!

Is it possible to have blocking for toasts, so only 1 is renderred?

As the title suggests, is it possible to limit the number of toasts displayed to some integer value? So subsequent triggers of toast() will be blocked. I did not come across anything in the docs which implied this, so I was wondering if there's any way to implement this. Thanks! (great package by the way!)

Example of Custom Promise Toast?

Is it possible to create a custom promise toast? I'd like to add a Dismiss button to all the toasts so I am using the custom toast mentioned in the documentation. However, when it comes to a custom promise toast, doesn't the promiseFunc() passed in to the promise toast take the place of the custom toast function?

Omit certain types of toasts

Is there a way in toast.promise(...) to only show the success / error toasts and not the loading toast? The current ways I see are to either set the duration to 0 or auto dismiss, which actually renders it for a second before it goes away. Can I configure it to just not show the loading toast in some scenarios?

Calling toast.promise() in componentDidMount()

Hi, I'm having an issue using toast.promise() and I can't figure out what's wrong with my code. The loading toast doesn't get displayed at all. The success/error toasts appear after the fetch is complete, all good here.

Weirdly, if I uncomment the toast("Hey") (see code below) in the render function, then the loading toast is displayed too (there's also a number that appears on top of the page).

Steps to reproduce on a fresh React install:

  1. npx create-react-app toaster-example
  2. cd toaster-example
  3. npm install react-hot-toast
  4. Use the following code in src/App.js:
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import toast, { Toaster } from "react-hot-toast";

const notify = () => toast("Here is your toast.");

class App extends React.Component {
  componentDidMount() {
    console.log("mounted");

    // Random API from https://github.com/public-apis/public-apis
    const fetchPromise = fetch(`https://randomfox.ca/floof/`);
    toast.promise(fetchPromise, {
      loading: "Loading",
      success: "Got the data",
      error: "Error when fetching",
    });
  }
  render() {
    return (
      <div className="App">
        {/* {toast("Hey")} */}
        <Toaster />
        <header className="App-header">
          <button onClick={notify}>Make me a toast</button>
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

Thanks

Toast not popping up

I'm trying to use the toast inside a view that is inside a modal, The full structure it's something like this:

<ModalBase>
  <ModalOverlay>
    <ModalBox>
      <View>
    </ ModalBox>
  </ ModalOverlay>
</ ModalBase>

I want to use it inside view which is something like this:

<>
  <Toaster position="bottom-center" />
  <OtherContent>
    ...
    <button onClick={handleClick} ... />
  </ OtherContent>
</>

Where

handleClick = () => {
 ...
 toast('test message');
}

Also I've tried with toast.success(...)

I'm importing like this: import toast, { Toaster } from 'react-hot-toast'; and I'm using typescript

Custom variants of toast when using headless mode

Hi! Is it possible to provide any custom variants of toast with the headless mode? It would be great, if we could create Notifications component and have own success, error and other toast's variants to use it, as:

toast.custom('My custom toast variant')

Question: How to prevent Toast re-render when use history.push or use onClick event on react Link component?

Hi, I have the Toaster set up like this:

in CreateBook.js

import React from 'react'
import { Link } from 'react-router-dom'
import toast, { Toaster } from 'react-hot-toast'

export default CreateBook() {
  // something code
  const handleSubmit = () => {
    toast.success('Clicked!')
  }

  return (
    <>
      Something content...
      <button onClick={handleSubmit}>Submit</button>
      <Link to='/home' title='Home.js'>Home</Link>
      <Toaster />  
    </>
  )
}

in Home.js

import React from 'react'
import { Link } from 'react-router-dom'
import toast, { Toaster } from 'react-hot-toast'

export default Home() {
  // something code

  return (
    <>
      Something content...
      <Link to='/create-book' title='CreateBook.js'>CreateBook</Link>
      <Toaster />  
    </>
  )
}

Toast component re-render when i quickly click the 'Home' link after I clicked the 'Submit' button.

How can I prevent this from happening?
Is there a similar method to toast.remove() auto run when the CreateBook component unmount?

Toast position relative to container?

No matter where Toaster is placed its' position is relative to the main document, is there a way to make it relative to the specific container?

For example if I have this structure:

<div className='main'>
   <div className='leftMenu'>
   </div>
   <div className='content'>
      <Toaster />
   </div>
</div>

and let's say leftMenu have 20% width and mainContent have 80% width, I wish centered toast would appear center to the 'content' - so 60% from left side of the screen, not relative to 'mainWrapper' (50% from left side of the screen).

Return 1 toast for each element in an array

I have an express api that returns an array with one element per each error.

Is it possible to display/pop up a toast for every element in an array?

API Response [ 'Email is required', 'Email is not valid', 'Password is required' ]

Currently using toast.promise()

No default Export

I'm getting an issue where the *.d.ts file doesn't have a default export and I'm getting the next error:

ERROR in [at-loader] ./node_modules/react-hot-toast/dist/components/toaster.d.ts:2:8
TS1192: Module '"/.../node_modules/csstype/index"' has no default export.

Set duration for dismiss-able toast

Hi, Looks like when set duration of toast (for my case toast.error()) it's not dismiss-able by click on toast.

toast.error(
  "oh, error!",
  { duration: 1000 * 60 }
);

toast.dimiss

Thanks for this great library!

I think this is more like a question. When toast.dismiss is called, a toast is dismissed after 1s, but if a new toast is created fast enough after dismissed is called, the toast will be dismissed almost immediately. Should creating a new toast be disabled while the dismissing animation is still in effect?

Does not work with Preact

Hi, I was trying out the plugin and the basic 'Getting Started' code fails to launch the toast for me.

I verified that the component renders properly, but it seems like the toast function is failing silently. Is there a way to turn on debug/error messages so that I can figure out what's going on?

Here's the full code I used for reference:

import React from 'react';

import toast, { Toaster } from 'react-hot-toast';
const notify = () => toast('Here is your toast.');

const App = () => {
  return (
    <div>
      <button onClick={notify}>Make me a toast</button>
      <Toaster />
    </div>
  );
};

export default App;

Add autodismissal time-to-live progress bar

This is really cool, ui.dev's newsletter brought me here!

I'm just missing a few features so I'll be making a few issues to keep track of that, starting with this one:

Feature request

A time-to-live progress bar would make the UX of autodismissal of toasts after a specified duration significantly clearer. The bar should be full when the toast appears and empty out until the specified toast duration passes (when the toast is autodismissed).

Avoid exposing `dispatch` from the library

Hi, thanks for this amazing library.

I have noticed that you expose your internal implementation of dispatch. Haven't investigated if there is a proper reason for doing this, but from the DX point of view it's terrible because all projects that use Redux with VS Code will import it by mistake when what they want to do is really:

const { dispatch } = props;

or

const dispatch = useDispatch();

I would consider not exporting your lib's internal dispatch to outside users of the lib.

Redux - How to use react-hot-toast with async await Axios call

hey guys, I saw the other question about this but it did not help me. I have tried multiple ways to get this to work but cannot seem to make it work.

I tried this:

export const postVersionBulkAction = (args) => {
	let url = `${apiBase}/smart-list/version/${args.versionId}/action`
	let promise = queue.wrap(async (dispatch) => {
		let params = { iabCategoriesActions: args.iabCategoriesActions }
		const result = await axios.patch(url, params)
		if (result.status === 200) {
		}
	})
	toast.promise(promise, {
		loading: 'Saving...',
		success: 'saved',
		error: 'error'
	})
}

but that gives me an error: 'TypeError: promise.then is not a function'

I've also tried this:

export const postVersionBulkAction = (args) => {
	let url = `${apiBase}/smart-list/version/${args.versionId}/action`
	return queue.wrap(async (dispatch) => {
		try {
			let params = { iabCategoriesActions: args.iabCategoriesActions }
			const result = await axios.patch(url, params)
			toast.promise(result, {
				loading: 'Saving...',
				success: 'saved',
				error: 'error'
			})
		} catch (error) {
			alert(error)
		}
	})
}

but i get 'promise.then is not a function' error on that one too.

I've also tried calling it like this:

	const promise = props.postVersionBulkAction(params)		
		toast.promise(promise, {
			loading: 'Saving...',
			success: <b>saved!</b>,
			error: <b>Could not apply.</b>
		})

but that way always fires the success toast even if it fails.

Any idea how i could make this work?

PS. thanks for the awesome product! Other than this problem it has helped me so much, and I have succesfully removed thousands of lines of redux boilerplate because of this library. thanks again

Can i use it with React Native?

Hii, React Hot Toast team, I see this project to be really awesome and an example of really good work.

Is the React Hot Toast add on Stable or useable for React Native?

Various (dis)appearance animations

Feature request

The current animation is really cool, but doesn't work as well visually when the toast in not centered on the page and has a bouncy feel that may not be suitable to all websites. There should be other options to choose from.

Make toast.promise accept optional message types

At the moment loading is required for any toast.promise calls, but what if someone wants to use toast.promise but doesn't want to show a toast for the loading state but only for the success or error state?

toast.promise = <T>(
promise: Promise<T>,
msgs: {
loading: Renderable;
success: ValueOrFunction<Renderable, T>;
error: ValueOrFunction<Renderable, any>;
},
opts?: DefaultToastOptions
) => {
const id = toast.loading(msgs.loading, { ...opts, ...opts?.loading });

containerStyle prop in Toaster

I need to customize some of the styling for the toast container. I don't see anything in the documentation, but I found containerStyle in the Toaster component below, however, it doesn't seem to do anything when passing it into the Toaster component.

Is there a reason this is here?

...containerStyle,

Add persistent toasts

Sometimes we need to show toast until it's dismissed by user or programmatically. E. g. connection lost and notification is shown until it's back online. Or some long or slow process happens.

It is not always possible to use toast.promise for that. Currently I use very long duration to simulate persistent toast.

Is it possible to add persistent toast, which doesn't have any timers inside them? Then it would possible to do:

const id = toast('No connection.', { persistent: true });

toast('Connected.', { id, persistent: false })

Support for description ?

Hi,

First of all, let me say that this library is awesome !

I wanted to use it for a project, however I need a description to the toast, a bit like in tailwind ui, I thought of using the headless mode, but unless wraping your hook to allow for description, do you think of a better way ?

Thanks a lot !

cant find variable document on React Native

Hey,

Iam trying to use this library inside react-native, however I keep getting

Can't find variable: Document

I have this notifcation component:

import { MaterialIcons } from '@expo/vector-icons'
import React, { useRef } from 'react'
import { useToaster } from 'react-hot-toast'
import { Animated, Text, View } from 'react-native'

const Toast = ({ t, updateHeight, offset }) => {
  const fadeAnim = useRef(new Animated.Value(0.5)).current // Initial value for opacity: 0
  const posAnim = useRef(new Animated.Value(-80)).current // Initial value for opacity: 0

  React.useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: t.visible ? 1 : 0,
      duration: 300,
      useNativeDriver: true,
    }).start()
  }, [fadeAnim, t.visible])

  React.useEffect(() => {
    Animated.spring(posAnim, {
      toValue: t.visible ? offset : -80,
      useNativeDriver: true,
    }).start()
  }, [posAnim, offset, t.visible])

  return (
    <Animated.View
      pointerEvents='none'
      style={{
        position: 'absolute',
        left: 0,
        right: 0,
        zIndex: 9999,
        alignItems: 'center',
        opacity: fadeAnim,
        transform: [
          {
            translateY: posAnim,
          },
        ],
      }}>
      <View
        onLayout={(event) =>
          updateHeight(t.id, event.nativeEvent.layout.height)
        }
        style={{
          marginTop: 50,
          backgroundColor: t.type === 'success' ? '#4caf50' : '#f44336',
          maxWidth: '80%',
          borderRadius: 30,
          flexDirection: 'row',
          alignItems: 'center',
          paddingVertical: 8,
          paddingHorizontal: 12,
        }}
        key={t.id}>
        <MaterialIcons
          name={t.type === 'success' ? 'check-circle-outline' : 'error-outline'}
          size={24}
          color='white'
        />
        <Text
          style={{
            color: '#fff',
            padding: 4,
            flex: 1,
            textAlign: 'center',
          }}>
          {t.message}
        </Text>
      </View>
    </Animated.View>
  )
}

const Notification = () => {
  const { toasts, handlers } = useToaster()

  return (
    <View
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
      }}>
      {toasts.map((t) => (
        <Toast
          key={t.id}
          t={t}
          updateHeight={handlers.updateHeight}
          offset={handlers.calculateOffset(t.id, {
            reverseOrder: false,
          })}
        />
      ))}
    </View>
  )
}

export default Notification

and I use that instead of <Toaster />

Apart from that the only imports I do look like this:

import { toast } from 'react-hot-toast'

limit total number of toasts

Hey! Awesome library. Something that would be useful for me is an option to set the maximum number of visible toasts, that will automatically dismiss the oldest one when the maximum is reached.

I could do that with useToaster and a filter but then I would have to replicate everything else <Toaster /> already does, so I would prefer not to.

Allow customization of message container

This issue was original raised by @ambroseus in #5. It would be cool to replace the built-in Message container. It includes styles which are hard to get rid of at the moment.

Ideally you will be a able to provide a custom Component without having to go headless.

Data undefined when using context

Hello.

Can I use toast.promise() in conjunction with useState and useContext?. I'm getting a funny behavior when trying to set state on the success property.

const axiosPromise = publicFetch.post('/auth/login', {
      email,
      password,
    });
    toast.promise(axiosPromise, {
      loading: 'Authenticating',
      success: ({data}) => {
        setAuthInfo(data.data) // coming from React Context, here it errors out and says data is undefined.
        return '';
      },
      error: () => 'Error',
    });

When trying to set state, data is undefined, it only happens when using the set state function.

<Toaster /> duration prop not changing duration of the notification

Giving your nice react-hot-toast npm a run in a project I'm working on. We have a simplistic alerts system and just today started looking at libs to upgrade our UI. Trying yours out after reading a blurb from a @tylermcginnis newsletter.

We literally copied this code from your API page and tweaked the duration really long to 30 seconds (30000) while testing some other things but the duration doesn't seem to be honored:

<Toaster
  position="top-center"
  reverseOrder={false}
  toastOptions={{
    // Define default options
    style: {
      margin: '40px',
      background: '#363636',
      color: '#fff',
      zIndex: 1,
    },
    duration: 5000,
    // Default options for specific types
    success: {
      duration: 3000,
      theme: {
        primary: 'green',
        secondary: 'black',
      },
    },
  }}
/>

We will keep playing around with it and let you know if we determine it is something in our code.

Add ability to customise default toast messages

Hi @timolins ๐Ÿ‘‹

I was thinking that the following API would be nice to allow users to default to a certain toast message if none is provided:

// example API
<Toaster types=[{
  icon: ErrorIcon,
  defaultMessage: 'An error happened'
}]

// in this way one could do the following
toast.error()

// An alternative to this would be to wrap the `toast` object and export it in your application, e.g.
import { toast as toastHander } from 'react-hot-toast'

export const toast = {
  ...toastHandler,
  error: (message, opts) => toastHandler.error(message || 'Your default error message', opts)
}

What do you think?

Server error when using with Nextjs

Has anyone faced an issue when setting a position attribute to Toaster component? Error looks like 'Error: Objects are not valid as a React child (found: object with keys {position}). If you meant to render a collection of children, use an array instead.'

set z index

I am currently using the modals provided by react semantic ui. There is a prop for a modal which makes the blurred. (https://react.semantic-ui.com/modules/modal/).

When I use it, my toasts won't appear, they are "behind" the blurred content. Is there a way to set the z index on the toasts or make them available up front?

Example with async/await

I'm wondering what to give notify.promise when using async/await where I need to access the result. Could you give us an example?

Example:

const onSubmit = async (data) => {
  const { key } = await createProject(data)

  // Now here comes the question:
  notify.promise('What would I possibly use here', {
    loading: 'Loading',
    success: 'Got the data',
    error: 'Error when fetching',
  })

  push(`/projects/${key}`)
}

Does toast() cause a re-render?

Hi, Found this a while back and am interested in using it for my next project. Building an SPA app and I have the Toaster set up like this:

index.js:

import React from 'react';
import { Toaster } from 'react-hot-toast';

const queryClient = new QueryClient()
ReactDOM.render(
	<React.StrictMode>
			<BrowserRouter>
				<Routes>
					<Route path='/login' element={<Login />} />
					<Route path='/' element={<Dashboard />} />
				</Routes>
			</BrowserRouter>
			<Toaster />
	</React.StrictMode>,
	document.getElementsById('root')
);

Then in my login component I get an isError bool value back from my query and I have the following in my render component:

return (
		<Layout>
			{isError && toast(error.toString())}
                         // render rest of content
)

I keep getting this issue:

index.js:1 Warning: Cannot update a component (Toaster) while rendering a different component (Login). To locate the bad setState() call inside Login, folow the stack trace as described in.

Anyway to get around this?

Add dismissal button

Feature request

It'd be greatly useful if toasts had an "X" button or something like that to dismiss them early. That can already be done with the API, but a built-in button would be great.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.